Derek Jones | 8ede1a2 | 2011-10-05 13:34:52 -0500 | [diff] [blame] | 1 | ################### |
| 2 | Running via the CLI |
| 3 | ################### |
| 4 | |
| 5 | As well as calling an applications :doc:`Controllers <./controllers>` |
| 6 | via the URL in a browser they can also be loaded via the command-line |
| 7 | interface (CLI). |
| 8 | |
| 9 | - `What is the CLI? <#what>`_ |
| 10 | - `Why use this method? <#why>`_ |
| 11 | - `How does it work? <#how>`_ |
| 12 | |
| 13 | What is the CLI? |
| 14 | ================ |
| 15 | |
| 16 | The command-line interface is a text-based method of interacting with |
| 17 | computers. For more information, check the `Wikipedia |
| 18 | article <http://en.wikipedia.org/wiki/Command-line_interface>`_. |
| 19 | |
| 20 | Why run via the command-line? |
| 21 | ============================= |
| 22 | |
| 23 | There are many reasons for running CodeIgniter from the command-line, |
| 24 | but 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 | |
| 34 | Let's try it: Hello World! |
| 35 | ========================== |
| 36 | |
| 37 | Let's create a simple controller so you can see it in action. Using your |
| 38 | text editor, create a file called tools.php, and put the following code |
| 39 | in it: |
| 40 | |
| 41 | <?php class Tools extends CI_Controller { public function message($to = |
| 42 | 'World') { echo "Hello {$to}!".PHP_EOL; } } ?> |
| 43 | Then save the file to your application/controllers/ folder. |
| 44 | |
| 45 | Now normally you would visit the your site using a URL similar to this:: |
| 46 | |
| 47 | example.com/index.php/tools/message/to |
| 48 | |
| 49 | Instead, we are going to open Terminal in Mac/Lunix or go to Run > "cmd" |
| 50 | in Windows and navigate to our CodeIgniter project. |
| 51 | |
| 52 | $ cd /path/to/project; |
| 53 | $ php index.php tools message |
| 54 | |
| 55 | If you did it right, you should see Hello World!. |
| 56 | |
| 57 | $ php index.php tools message "John Smith" |
| 58 | |
| 59 | Here we are passing it a argument in the same way that URL parameters |
| 60 | work. "John Smith" is passed as a argument and output is: Hello John |
| 61 | Smith!. |
| 62 | |
| 63 | That's it! |
| 64 | ========== |
| 65 | |
| 66 | That, in a nutshell, is all there is to know about controllers on the |
| 67 | command line. Remember that this is just a normal controller, so routing |
| 68 | and _remap works fine. |