Laravel 5.5 Package Development

Laravel 5.5 Package Development

 

Laravel packages are awesome mainly because of the efficiency they add to development. For example, when it comes to using a functionality or library in more than one project, we can create a Laravel package and use it in any Laravel application, instead of writing the same code every time.

Considering the number of developers whose lives can be eased by Laravel, I decided to write this blog and provide a step by step guide to developing a Laravel package.

 

This article will give you the insights on how to-

 

Let’s get coding!

 

1.  Create a basic structure of the Laravel package

  • The first step begins with creating a new Laravel application.
composer create-project laravel/laravel --prefer-dist .

 

  • Next,  create /packages folder in the root directory of Laravel, where you will be keeping your package.
  • Now,  create a folder with “[creator]/[package_name].This is similar to any packages you have seen in the market. You can even use your GitHub name as the creator name.
  • In this example, I will be creating a small library which will expose the function and will perform certain task. The task can be anything like using any SDK(s), like Facebook SDK, etc.
  • Since we are trying to expose the function to connect with facebook let’s call this package “Facebook”
  • Once the package is created, it will look like this-
[packages]/[think201]/[facebook]

Here,  “think201” is the creator name, and “facebook” is the package name.

  • Once the package is created, create “/src” folder inside the package
[packages]/[think201]/[facebook]/src

“src” is the main folder where all our code will be.

The structure will look like this-

Laravel - Packages
  • Now, to create “composer.json” file for the  package, navigate to your package main directory and run composer init
  • Provide the name for the package, in this case, “think201/facebook”.
  • Once you fill in all the details being asked, your “composer.json” file will look similar to below image-
Laravel - Think201 Facebook
{

    "name": "think201/facebook",

    "description": "Facebook SDK",

    "type": "library",

    "license": "MIT",

    "minimum-stability": "dev",

    "authors": [{

        "name": "Think201",

        "email": "vivek@think201.com"

    }],

    "require": {

        "php": ">=5.6.4"

    },

}

 

2. Register Service Provider to boot up the Laravel package

  • Once the structure is created,  create a service provider which will register and boot up the package.
  • Create a Service Provider, like FacebookServiceProvider.php. You can even use the inbuilt command to create service provider-
[packages]/[think201]/[facebook]/FacebookServiceProvider.php
  • The Service provider file will be inside “src” folder.

3. Create Routes

This step explains you as to how to create a route and register it.

Here’s how the service provider will look like without writing any logic into it-

Laravel

 

<?php

namespace Think201\Facebook;

use Illuminate\Support\ServiceProvider;

use Think201\Facebook\Library\Facebook;

class FacebookServiceProvider extends ServiceProvider {

/**

 * Bootstrap the application services.

 *

 * @return void

 */

public function boot() {

}

/**

 * Register the application services.

 *

 * @return void

 */

public function register() {

}

}
  • First, create a folder inside “src” folder with routes and then create a web.php file where we will write our route entries
[packages]/[think201]/[facebook]/routes/web.php

It will look like this-

Laravel - Packages 2
  • Now, in order to test the route file- I am going to create a route “/facebook” which will return an array with Facebook credentials. For now, I am using a callback function in route to make it simple-

 

<?php

Route::get('/facebook', function () {

return [

'facebook_id' => 2234554654665654,

'facebook_secret_key' => '5fdgjnkjndfkgj897644358vtjktret',

'callback_url' => 'https://think201.com/facebook_callback',

];

});

 

  • Lets, register the route in the service provider file in boot function, so that it will be available for Laravel

 

$this->loadRoutesFrom(__DIR__ . '/routes/web.php');

 

  • We are now done with routes and you need to add your service provider class in your “config/app.php” in provider list so that it will be accessible.

 

Think201\Facebook\FacebookServiceProvider::class,

 

  • Run the Composer dumpautoload to make sure the classes are loaded and there are no issues in it.
  • When you now  navigate to yourdomain/facebook, you will see the array returning with Facebook credentials which we added in our routes file.

 

4. Create a Controller to consume Routes

What we would do here is to create controller which would resolve the route request & perform defined tasks in it.

  • Start by creating a file named FacebookController.php inside-

 

[packages]/[think201]/[facebook]/src/FacebookController.php

 

Tip  You can also create controller using artisan command and then move it to package dir-

 

[packages]/[think201]/[facebook]/src/

 

  • Once you have created controller file  inside “[packages]/[think201]/[facebook]/src/” folder ensure you call controller function from the route to access the view file or return the data.
  • A crucial thing here is to register the controller so that it will be accessible. Therefore, we need to update our service provider class.
  • Add a line in our register method of service provider class –

 

$this->app->make('Think201\Facebook\FacebookController');

 

The Controller is now ready to be consumed.

5. Register Facade

  • First, create a facade class named “Facebook”-

 

[packages]/[think201]/[facebook]/src/Facade/Facebook.php
Laravel - Facebook Php

 

<?php

namespace Think201\Facebook\Facades;

use Illuminate\Support\Facades\Facade;

class Facebook extends Facade {

public static function getFacadeAccessor() {

return 'fbm';

}

}
  • Here, we are extending the Facade Class to use “getFacadeAccessor” function and then we are returning “fbm”.
  • fbm is a keyword which we will use in our service provider register method and register facade.

 

public function register() {

$this->app->bind('fbm', function ($app) {

return new Facebook(config('facebook'));

});

}

 

6. Use Facades to call the Library Function

  • Here “new Facebook” is a library class where we will expose our function so that those can be consumed in our application.
  • For that, you just have to create a folder Library inside our src folder and create “Facebook.php” class-

 

[packages]/[think201]/[facebook]/src/Library/Facebook.php

 

  • And now, to expose the function, for example let’s create a function which will return facebook credentials

 

<?php

namespace Think201\Facebook\Library;

/**

 *

 */

class Facebook {

private $fbid;

private $fbsecret;

private $fburl;

public function __construct($fb) {

$this->fbid = $fb['id'];

$this->fbsecret = $fb['secret'];

$this->fburl = $fb['url'];

}

public function getCreds() {

return [

'fb_id' => $this->fbid,

'fb_secret' => $this->fbsecret,

'fb_url' => $this->fburl,

];

}

}

 

7. Create a config file and deploy it to the actual application on Vendor publish

  • We will be using our config to assign the credentials to our library.
  • Create a config file so that the user can provide Facebook credentials from the config file.
  • For this, create a “Config” folder inside src and create facebook.php file and return the array with credentials-

 

[packages]/[think201]/[facebook]/src/Config/facebook.php
  • Like Below-

 

<?php

return [

'id' => '3443432442343423',

'secret' => 'kjsdfdsbfjdfdsfut7tf87dstf',

'url' => 'http://think201.com',

];
Laravel - Php Return 
  • And in the “FcebookServiceProvider.php” class, add and publish method in boot function so that when the user runs the vendor publish command, the config file gets copied to “config dir” for the application user as follows-
$this->publishes([

__DIR__ . '/Config/facebook.php' => config_path('facebook.php'),

]);
  • Also, run the command php artisan vendor:publish” and then choose the package to publish the config file.

 

This is how the complete FacebookServiceProvider.php file will look like-

 

Laravel - php 3

 

<?php

namespace Think201\Facebook;

use Illuminate\Support\ServiceProvider;

use Think201\Facebook\Library\Facebook;

class FacebookServiceProvider extends ServiceProvider {

/**

 * Bootstrap the application services.

 *

 * @return void

 */

public function boot() {

$this->loadRoutesFrom(__DIR__ . '/routes/web.php');

$this->publishes([

__DIR__ . '/Config/facebook.php' => config_path('facebook.php'),

]);

}

/**

 * Register the application services.

 *

 * @return void

 */

public function register() {

$this->app->bind('fbm', function ($app) {

return new Facebook(config('facebook'));

});

}

}

 

8. Call Facade to access the Functionality

  • This is the last step. Here, we need to register this in our “config/app.php” so that it will be available to consume throughout the application-

 

'FBM' => Think201\Facebook\Facades\Facebook::class,

 

  • Also, change the route file and use the Facade

 

<?php

Route::get('/facebook', function () {

return FBM::getCreds();

});

 

This is how the package folder directory will look like-

Laravek - Packages 4

Now, do a composer dump autoload and voila! We are ready with the laravel package.

 

Hope this blog on Laravel package development has helped you with your first successful creation. Feel free to ask any queries on https://twitter.com/vivek0460