Custom Commands

Projects often have a need for customized command line accessible scripts, may it be to be called from a cron or manually from the command line.

Generating a custom command

Using the command line, run the generate command from your project’s base directory. Here we create a command called bundle.

$  ./strata generate command bundle

The command will create a new class in the src/Shell directory.

Scaffolding command BundleCommand
  ├── [ OK ] src/Shell/Command/BundleCommand.php
  └── [ OK ] test/Shell/Command/BundleCommandTest.php

Executing

Custom commands are being auto-loaded when you call the script. Therefore, the previous bundle script can be called using:

$  ./strata bundle

Requirements

StrataCommand inherit from Symfony’s Console component. You will have to use their classes to manipulate input and output data.

The class needs to have a configure() function that declares the command name and description as well as potential parameters. It also requires a function called execute() that will run when the command is called.

More information can be found in Symfony’s documentation.

Example

The following is an example bundle command. It goes through all the themes installed on the current project and executes installation scripts of known frontend libraries.

Looking at this class should give you a good understanding of what is possible with custom commands.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<?php
namespace App\Shell\Command;

use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * The bundle command will ensure the application is correctly configured
 * when the project is first setup.
 */
class BundleCommand extends \Strata\Shell\Command\StrataCommand {

    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            ->setName('bundle')
            ->setDescription('Bundles the project frontend files');
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->startup($input, $output);
        $this->bundleThemesFrontend();
        $this->shutdown();
    }

    private function bundleThemesFrontend()
    {
        foreach ($this->getThemesDirectories() as $themePath) {
            $this->bundleFrontend($themePath);
        }
    }

    private function getThemesDirectories()
    {
        return glob("web/app/themes/*/");
    }

    /**
     * Goes in the directory and bundles the frontend tools
     * @param  string $themePath
     */
    private function bundleFrontend($themePath)
    {
        $this->output->writeln("Creating frontend bundle for <info>$themePath</info>");
        exec("cd $themePath && npm install && bower install && grunt dist");
        $this->nl();
    }
}
?>