Tasks

Contents

The Basics

Laravel's command-line tool is called Artisan. Artisan can be used to run "tasks" such as migrations, cronjobs, unit-tests, or anything that you want.

Creating & Running Tasks

To create a task create a new class in your application/tasks directory. The class name should be suffixed with "_Task", and should at least have a "run" method, like this:

Creating a task class:

  1. class Notify_Task {
  2.  
  3. public function run($arguments)
  4. {
  5. // Do awesome notifying…
  6. }
  7.  
  8. }

Now you can call the "run" method of your task via the command-line. You can even pass arguments:

Calling a task from the command line:

  1. php artisan notify

Calling a task and passing arguments:

  1. php artisan notify taylor

Calling a task from your application:

  1. Command::run(array('notify'));

Calling a task from your application with arguments:

  1. Command::run(array('notify', 'taylor'));

Remember, you can call specific methods on your task, so, let's add an "urgent" method to the notify task:

Adding a method to the task:

  1. class Notify_Task {
  2.  
  3. public function run($arguments)
  4. {
  5. // Do awesome notifying…
  6. }
  7.  
  8. public function urgent($arguments)
  9. {
  10. // This is urgent!
  11. }
  12.  
  13. }

Now we can call our "urgent" method:

Calling a specific method on a task:

  1. php artisan notify:urgent

Bundle Tasks

To create a task for your bundle just prefix the bundle name to the class name of your task. So, if your bundle was named "admin", a task might look like this:

Creating a task class that belongs to a bundle:

  1. class Admin_Generate_Task {
  2.  
  3. public function run($arguments)
  4. {
  5. // Generate the admin!
  6. }
  7.  
  8. }

To run your task just use the usual Laravel double-colon syntax to indicate the bundle:

Running a task belonging to a bundle:

  1. php artisan admin::generate

Running a specific method on a task belonging to a bundle:

  1. php artisan admin::generate:list

CLI Options

Setting the Laravel environment:

  1. php artisan foo --env=local

Setting the default database connection:

  1. php artisan foo --database=sqlite