Last active
February 12, 2025 17:04
-
-
Save phenaproxima/182b7d5f23d3c3e17879057d20877bb1 to your computer and use it in GitHub Desktop.
How to programmatically apply a Drupal recipe (works in 10.3 and later)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Drupal\Core\Batch\BatchBuilder; | |
use Drupal\Core\Recipe\Recipe; | |
use Drupal\Core\Recipe\RecipeRunner; | |
// There are two ways to apply a recipe programmatically: immediately, or as a batch job. | |
// The batch job is generally the safer option, since more complex recipes could risk | |
// timing out if they try to do too much at once. | |
// So, first thing you need to do is get a Recipe object. Point it to the directoy where | |
// recipe.yml is: | |
$recipe = Recipe::createFromDirectory('/path/of/some/recipe'); | |
// Now, if you want to make that a batch job: | |
$batch = new BatchBuilder(); | |
foreach (RecipeRunner::toBatchOperations($recipe) as $operation) { | |
$batch->addOperation(...$operation); | |
} | |
// Maybe you do other stuff with $batch here, like adding more operations, setting up the messages, etc. | |
// Finally, to kick off the job: | |
batch_set($batch->toArray()); | |
// And that's that. | |
// If you want to just immediately apply the recipe, without giving the user any feedback, that's even | |
// easier: | |
RecipeRunner::processRecipe($recipe); | |
// Done-zo. | |
// By the way, BOTH of these techniques will automatically apply all the recipes that $recipe depends upon. You don't | |
// have to worry about setting it up or recursing or any of that nonsense. Just let the recipe system handle it for you. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment