BazylPL
BazylPL

Reputation: 238

Custom maker in Symfony MakerBundle

In Symfony MakerBundle docs there is a word about creating own makers. It says to:

create a class that extends AbstractMaker in your src/Maker/ directory. And this is really it!

Slow down there. What about a custom template/skeleton for this new maker? I checked in Symfony\Bundle\MakerBundle\Generator class and it searches for templates like this:

$templatePath = __DIR__.'/Resources/skeleton/'.$templateName;

So when running custom maker (command) the path is still set to Symfony MakerBundle resources. Am I missing something? No clean way to generate files from custom templates?

Upvotes: 0

Views: 537

Answers (1)

Julien B.
Julien B.

Reputation: 3334

Well if I look at the code in Symfony\Bundle\MakerBundle\Generator I see this:

 private function addOperation(string $targetPath, string $templateName, array $variables)
    {
        if ($this->fileManager->fileExists($targetPath)) {
            throw new RuntimeCommandException(sprintf('The file "%s" can\'t be generated because it already exists.', $this->fileManager->relativizePath($targetPath)));
        }

        $variables['relative_path'] = $this->fileManager->relativizePath($targetPath);

        $templatePath = $templateName;
        if (!file_exists($templatePath)) {
            $templatePath = __DIR__.'/Resources/skeleton/'.$templateName;

            if (!file_exists($templatePath)) {
                throw new \Exception(sprintf('Cannot find template "%s"', $templateName));
            }
        }

        $this->pendingOperations[$targetPath] = [
            'template' => $templatePath,
            'variables' => $variables,
        ];
    }

So basically, it first checks if the file exists, if it doesn't it changes the template's path to __DIR__.'/Resources/skeleton/'.$templateName; and if that file doesn't exist either, it then throws an exception.

So basically, if you provide a file path that exists to the $templateName argument, you can decide where the template is loaded from.

Upvotes: 1

Related Questions