Creating artisan commands in Laravel

This is part of a two part series in fetching Delicious bookmarks into Laravel. in this part we create our new console command for fetching bookmarks and the class for handling them.

Creating commands is also my favourite way of creating new functionality when we’re working with an API, so let’s get started and create our bookmark fetching command.

php artisan make:console BookmarksFetch 

Add our command to the kernel (/app/Console/Kernel.php)

     protected $commands = [
         \App\Console\Commands\Inspire::class,
         \App\Console\Commands\BookmarksFetch::class
     ];

Open up /app/Console/Commands/BookmarksFetch.php

Edit the signature and description

protected $signature = 'bookmarks:fetch’;
protected $description = 'Fetch bookmarks from Delicious’;

That’s it, our command is now available in php artisan, go ahead take a look.

 bookmarks
  bookmarks:fetch     Fetch bookmarks from Delicious

We’re going to do one last thing, we’re going to create a class for delicious in our commands directory.

<?php namespace App\Console\Commands;

class Delicious {
   public function fetch() {
	echo “This is is a test”;
   }

}?>

Let’s update the handle function of our command here and use it to inject our new delicious class through the IOC before calling the fetch method of it.

   /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle(Delicious $delicious)
    {
        $delicious->fetch();
    }
}

Perfect, let’s run the command check everything is connected together!

$ php artisan bookmarks:fetch
This is a test%                        

Now move on to the next part in this series where we pull in the bookmarks authenticating OAuth2 with Delicious.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.