Running via the Command Line

As well as calling an application’s Controllersvia the URL in a browser they can also be loaded via the command-lineinterface (CLI).

What is the CLI?

The command-line interface is a text-based method of interacting withcomputers. For more information, check the Wikipediaarticle.

Why run via the command-line?

There are many reasons for running CodeIgniter from the command-line,but they are not always obvious.

  • Run your cron-jobs without needing to use wget or curl.
  • Make your cron-jobs inaccessible from being loaded in the URL bychecking the return value of is_cli().
  • Make interactive “tasks” that can do things like set permissions,prune cache folders, run backups, etc.
  • Integrate with other applications in other languages. For example, arandom C++ script could call one command and run code in your models!

Let’s try it: Hello World!

Let’s create a simple controller so you can see it in action. Using yourtext editor, create a file called Tools.php, and put the following codein it:

  1. <?php namespace App\Controllers;
  2.  
  3. use CodeIgniter\Controller;
  4.  
  5. class Tools extends Controller {
  6.  
  7. public function message($to = 'World')
  8. {
  9. echo "Hello {$to}!".PHP_EOL;
  10. }
  11. }

Then save the file to your app/Controllers/ directory.

Now normally you would visit your site using a URL similar to this:

  1. example.com/index.php/tools/message/to

Instead, we are going to open Terminal in Mac/Linux or go to Run > “cmd”in Windows and navigate to our CodeIgniter project’s web root.

  1. $ cd /path/to/project/public
  2. $ php index.php tools message

If you did it right, you should see Hello World! printed.

  1. $ php index.php tools message "John Smith"

Here we are passing it an argument in the same way that URL parameterswork. “John Smith” is passed as an argument and output is:

  1. Hello John Smith!

That’s the basics!

That, in a nutshell, is all there is to know about controllers on thecommand line. Remember that this is just a normal controller, so routingand _remap() works fine.

However, CodeIgniter provides additional tools to make creating CLI-accessiblescripts even more pleasant, include CLI-only routing, and a library that helpsyou with CLI-only tools.

CLI-Only Routing

In your Routes.php file you can create routes that are only accessible fromthe CLI as easily as you would create any other route. Instead of using the get(),post(), or similar method, you would use the cli() method. Everything elseworks exactly like a normal route definition:

  1. $routes->cli('tools/message/(:segment)', 'Tools::message/$1');

For more information, see the Routes page.

The CLI Library

The CLI library makes working with the CLI interface simple.It provides easy ways to output text in multiple colors to the terminal window. It alsoallows you to prompt a user for information, making it easy to build flexible, smart tools.

See the CLI Library page for detailed information.