blob: 8fcf31702598142b2e032fa30c7dfd4a33897395 [file] [log] [blame]
Derek Jones8ede1a22011-10-05 13:34:52 -05001###################
2Running via the CLI
3###################
4
5As well as calling an applications :doc:`Controllers <./controllers>`
6via the URL in a browser they can also be loaded via the command-line
7interface (CLI).
8
9- `What is the CLI? <#what>`_
10- `Why use this method? <#why>`_
11- `How does it work? <#how>`_
12
13What is the CLI?
14================
15
16The command-line interface is a text-based method of interacting with
17computers. For more information, check the `Wikipedia
18article <http://en.wikipedia.org/wiki/Command-line_interface>`_.
19
20Why run via the command-line?
21=============================
22
23There are many reasons for running CodeIgniter from the command-line,
24but they are not always obvious.
25
26- Run your cron-jobs without needing to use wget or curl
27- Make your cron-jobs inaccessible from being loaded in the URL by
28 checking for ``$this->input->is_cli_request()``
29- Make interactive "tasks" that can do things like set permissions,
30 prune cache folders, run backups, etc.
31- Integrate with other applications in other languages. For example, a
32 random C++ script could call one command and run code in your models!
33
34Let's try it: Hello World!
35==========================
36
37Let's create a simple controller so you can see it in action. Using your
38text editor, create a file called tools.php, and put the following code
Derek Jones46715e52011-10-05 17:36:22 -050039in it::
Derek Jones8ede1a22011-10-05 13:34:52 -050040
Derek Jones46715e52011-10-05 17:36:22 -050041 <?php
42 class Tools extends CI_Controller {
43
44 public function message($to = 'World')
45 {
46 echo "Hello {$to}!".PHP_EOL;
47 }
48 }
49 ?>
50
Derek Jones8ede1a22011-10-05 13:34:52 -050051Then save the file to your application/controllers/ folder.
52
53Now normally you would visit the your site using a URL similar to this::
54
55 example.com/index.php/tools/message/to
56
57Instead, we are going to open Terminal in Mac/Lunix or go to Run > "cmd"
58in Windows and navigate to our CodeIgniter project.
59
Derek Jones46715e52011-10-05 17:36:22 -050060.. code-block:: bash
61
Derek Jones8ede1a22011-10-05 13:34:52 -050062 $ cd /path/to/project;
63 $ php index.php tools message
64
65If you did it right, you should see Hello World!.
66
Derek Jones46715e52011-10-05 17:36:22 -050067.. code-block:: bash
68
Derek Jones8ede1a22011-10-05 13:34:52 -050069 $ php index.php tools message "John Smith"
70
71Here we are passing it a argument in the same way that URL parameters
72work. "John Smith" is passed as a argument and output is: Hello John
73Smith!.
74
75That's it!
76==========
77
78That, in a nutshell, is all there is to know about controllers on the
79command line. Remember that this is just a normal controller, so routing
80and _remap works fine.