As a PHP developer, you may be interested in working with frameworks. Frameworks attempt to make the process of development easier by simplifying common practices used in the majority of developing web projects such as packages, modules, plug-ins, and even components (CakePHP).
Perhaps during the development process, you feel you are reinventing the wheel, such as when creating an Authentication or Captcha application. In this case, you need to create a package which will simplify and make your app development faster and easier.
There are two types of packages; some are framework independent (stand-alone) and the others are for a specific framework. This tutorial will exclusively cover Laravel packages.
Before creating a package you need to know about package managers. PEAR is a well-known PHP package manager which, although available, is rarely used. Why? It forced you to install packages system-wide, rather than on a project-by-project basis. Composer became PEAR’s successor.
What Are Laravel Packages?
One of the parameters for scaling framework power is how the developer redistributes useful packages of code. This allows developers to summarize applications into several packages of smaller applications.
Indeed, packages offer a great way to group related code. Packages are very similar to “Components”. It is important to note that the Laravel source code is a “package”, which Taylor Otwell calls the DEFAULT_BUNDLE
.
One great advantage of Laravel packages is that they allow access to all the features the framework offers to its host application, including routing, migrations, tests, views, and numerous other useful features. Another important advantage of a package is the DRY (Don’t Repeat Yourself) principle. By creating a package for code you frequently use, you save resources and improve your application’s performance.
Now let’s introduce some useful Laravel packages. Packages I have used include:
- Generators: One of the things I liked about CakePHP was its Bake feature. This is the closest thing I’ve found in any other framework.
- Ardent: Self-validating smart models for Eloquent ORM.
- IDE helper: This package seeks to rectify the code auto-completion issue in PhpStorm by creating a docblock helper file from which the IDE can take cues.
- Sayakb: It brings you a great captcha app.
- Behat: A solution for testing your application using the BDD methodology.
- Artdarek: A great OAuth wrapper.
- Mcamara: Easy i18n localization for your Laravel app.
You may find the packaging capability you need in packalyst. Packalyst creates a simple and social packages registry for Laravel.
How to Build Your Own Laravel Package
Create a simple authentication package for Laravel 5.0. To do this, first of all you need a composer.json
file for your new package:
{ "name": "alireza/myauth", "description": "How create your laravel 5 package", "license": "MIT", "authors": [ { "name": "Alireza Rahmani khalili", "email": "[email protected]" } ], "minimum-stability": "dev", "require": { "laravel/framework": "~5.0" }, "autoload": { "psr-4": { "Alireza\\Authentication\\": "src/" } } }
The Service Provider class is simply the file which sets everything up correctly for the package.
Here is what the Service Provider should look like at this point, in src/MyAuthServiceProvider.php
:
namespace Alireza\Authentication; use Illuminate\Support\ServiceProvider; class MyAuthServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Bootstrap the application events. * * @return void */ public function boot() { } /** * Register the service provider. * * @return void */ public function register() { } /** * Get the services provided by the provider. * * @return array */ public function provides() { return []; } }
Add the service provider to config/app.php
:
'Alireza\Authentication\MyAuthServiceProvider ::class',
Now Laravel is aware of the package. You may ask about “alias” and why I don’t add it to my app.php
. Personally, I add alias in the register method of the service provider class instead of adding it manually to the Laravel config file. I will address this later.
Now create a simple PHP class called MyAuth
in src/MyAuth.php
:
namespace Alireza\Authentication; use Config, Request, Session, Hash; use App\User; Class MyAuth { public $redirect_login = '/users/home'; public $redirect_logout = '/users/logout'; public $login = '/user/login'; protected $data; public function __construct() { if (Request::isMethod('post')) //Get post inputs $this->data = array('username' => Input::get('username'), 'password' => Input::get('password')); } public function login($data = false) { $this->data = $data; if ($this->data && !is_array($this->data)) return redirect($this->login)->with('message', 'sorry no array to log-in manually')->send(); if ($this->data && !Session::has('user')) { $result = User::Where(['email' => $this->data['username'] ]) ->first(); if ($result && Hash::check($this->data['password'], $result->password)) { Session::put('user', $result); return Redirect($this->redirect_login)->with('message', 'Welcome log-in succeeded ')->send(); } Session::flush(); return redirect($this->login)->with('message', 'Login Failed, wrong username or password')->send(); } } public function logout() { Session::flush(); return redirect($this->login)->with('message', 'logout succeeded')->send(); } }
The authentication class should bind with Laravel’s IoC Container to the service provider of the package. Before that, create a Facade class which will allow use of class methods without needing to create a new instance, as well as other benefits which were indicated earlier. Just as the MyAuth class created the new directory Facades
in the Facades directory, create a new PHP class and name it src/MyAuthFacade.php
:
namespace Alireza\Authentication; use Illuminate\Support\Facades\Facade; class MyAuthFacade extends Facade { protected static function getFacadeAccessor() { return 'MyAuth'; } }
After this, the only thing remaining is to bootstrap the package. Mine looks like:
public function register() { $this->app['MyAuth'] = $this->app->share(function($app) { return new MyAuth; }); $this->app->booting(function() { $loader = \Illuminate\Foundation\AliasLoader::getInstance(); $loader->alias('MyAuth', 'Alireza\Authentication\MyAuthFacade'); }); }
As you can see, I have bound the Myauth class with the IoC Container. Now it is easy use the MyAuth class:
MyAuth::login(['username'=>'[email protected]','password'=>'test']);
This should generate the message, Welcome log-in succeeded.
If desired, you can now register your package in Packagist. The MyAuth package has now been registered and can easily be included in Laravel via the composer command: composer require "alireza/myauth"
.
Conclusion
If you’re looking for an example of a popular, mature Laravel package, then you can check out TerranetAdmin for Laravel.
This was a short overview of how to create a Laravel 5 package. As you can see, creating the package is easy, and could be an important tool for simplifying and speeding up the development process.
Comments