Home Backend Development PHP Tutorial Laravel Composer Package 开发实战 toastr-for-laravel5

Laravel Composer Package 开发实战 toastr-for-laravel5

Jun 20, 2016 pm 12:39 PM

本文原链接来自我的博客,地址: Laravel Composer Package 开发实战 toastr-for-laravel5

在Laravel的文档中有Package Development,对于入门开发人员来说还是比较抽象,因为开发一个包需要了解 Service Providers,Service Providers 和 Facade 已经够抽象的了对刚接触Laravel的开发人员来说,所以我来写一个简单的Laravel 包开发的实例教程吧。

toastr.js是一个很方便的通知效果,最近刚发布了laravel 5.2,所以就来开发一个toastr for laravel 5的包吧,主要用toastr结合laravel的flash session来实现页面的一次性消息提醒,其实这个在我们日常开发中页面操作提醒还是很常用到的业务。

一般的laravel 包开发过程是这样的,开发好以后打包push到gitlab,然后在packagist上提交,下面我们就来一步一步实现这个过程。

1.在新建的laravel项目中建立如下目录 packages/yuansir/toastr/src ,packages 目录和 app 目录同级。我们开发包的代码都放在这个src目录中,yuansir和toastr完全自定义。

2.修改项目的composer.json,设定PSR-4命名空间:

"autoload": {        "classmap": [            "database"        ],        "psr-4": {            "App\\": "app/",            "Yuansir\\Toastr\\": "packages/yuansir/toastr/src/"        }    },
Copy after login

别忘了执行autoload

$ cd pacages/yuansir/toastr/src
Copy after login
Copy after login

3.为我们的包初始化一个composer.json文件,熟悉composer的应该都知道这玩意是干嘛的了

$ cd pacages/yuansir/toastr/src
Copy after login
Copy after login
按照提示填写相关信息,有些信息可以不用填写,后面自己在composer.json中添加就可以了,生成的示例如下:
{    "name": "ryan/toastr-for-laravel",    "description": "toastr.js for laravel5",    "authors": [        {            "name": "Ryan",            "email": "yuansir@live.cn"        }    ],    "require": {}}
Copy after login

4.开始开发,新建Service Provider

php artisan make:provider ToastrServiceProvider
Copy after login

将生成的app/Providers/ToastrServiceProvider.php文件移动到我们的packages/yuansir/toastr/src 目录下面,并注册ToastrServiceProvider到config/app.php 的providers 中。

'providers' => [        /*         * Laravel Framework Service Providers...         */         ......        /*         * Application Service Providers...         */         ......        Yuansir\Toastr\ToastrServiceProvider::class,    ],
Copy after login

5.新建packages/yuansir/toastr/src/config/toastr.php 来保存toastr.js的options,options配置还蛮多的,具体可以看它的demo。

<?php return [     'options' => []];
Copy after login

关于这个配置在我们包中如何调用的,我们过会来说.

6.新建Toastr类,来实现toastr 的info,success,error,warning的相关实现,代码还是很简单的,packages/yuansir/toastr/src/Toastr.php:

<?php namespace Yuansir\Toastr;use Illuminate\Session\SessionManager;use Illuminate\Config\Repository;class Toastr{    /**     * @var SessionManager     */    protected $session;    /**     * @var Repository     */    protected $config;    /**     * @var array     */    protected $notifications = [];    /**     * Toastr constructor.     * @param SessionManager $session     * @param Repository $config     */    public function __construct(SessionManager $session, Repository $config)    {        $this->session = $session;        $this->config = $config;    }    public function render()    {        $notifications = $this->session->get('toastr:notifications');        if(!$notifications) {            return '';        }        foreach ($notifications as $notification) {            $config = $this->config->get('toastr.options');            $javascript = '';            $options = [];            if($config) {                $options = array_merge($config, $notification['options']);            }            if($options) {                $javascript = 'toastr.options = ' . json_encode($options) . ';';            }            $message = str_replace("'", "\\'", $notification['message']);            $title = $notification['title'] ? str_replace("'", "\\'", $notification['title']) : null;            $javascript .= " toastr.{$notification['type']}('$message','$title');";        }        return view('Toastr::toastr', compact('javascript'));    }    /**     * Add notification     * @param $type     * @param $message     * @param null $title     * @param array $options     * @return bool     */    public function add($type, $message, $title = null, $options = [])    {        $types = ['info', 'warning', 'success', 'error'];        if(!in_array($type, $types)) {            return false;        }        $this->notifications[] = [            'type' => $type,            'title' => $title,            'message' => $message,            'options' => $options        ];        $this->session->flash('toastr:notifications', $this->notifications);    }    /**     * Add info notification     * @param $message     * @param null $title     * @param array $options     */    public function info($message, $title = null, $options = [])    {        $this->add('info', $message, $title, $options);    }    /**     * Add warning notification     * @param $message     * @param null $title     * @param array $options     */    public function warning($message, $title = null, $options = [])    {        $this->add('warning', $message, $title, $options);    }    /**     * Add success notification     * @param $message     * @param null $title     * @param array $options     */    public function success($message, $title = null, $options = [])    {        $this->add('success', $message, $title, $options);    }    /**     * Add error notification     * @param $message     * @param null $title     * @param array $options     */    public function error($message, $title = null, $options = [])    {        $this->add('error', $message, $title, $options);    }    /**     * Clear notifications     */    public function clear()    {        $this->notifications = [];    }}
Copy after login




7.我们看到view(‘Toastr::toastr’, compact(‘javascript’));,那么就是需要一个视图文件了,关于Toastr::toastr是什么鬼我们过会来说,新建 packages/yuansir/toastr/src/views/toastr.blade.php 视图文件:

<link href="http://cdn.bootcss.com/toastr.js/latest/css/toastr.min.css" rel="stylesheet"><script src="http://cdn.bootcss.com/toastr.js/latest/js/toastr.min.js"></script><script type="text/javascript">{!! $javascript !!}</script>
Copy after login
8.建立Facade,新建packages/yuansir/toastr/src/Facades/Toastr.php 就是引入了tastr插件,输出我们render方法中的$javascript
<?php namespace Yuansir\Toastr\Facades;use Illuminate\Support\Facades\Facade;class Toastr extends Facade{    protected static function getFacadeAccessor()    {        return 'toastr';    }}
Copy after login

9.修改ToastrServiceProvider:

<?php namespace Yuansir\Toastr;use Illuminate\Support\ServiceProvider;class ToastrServiceProvider extends ServiceProvider{    /**     * Bootstrap the application services.     *     * @return void     */    public function boot()    {        $this->loadViewsFrom(__DIR__ . '/views', 'Toastr');        $this->publishes([            __DIR__.'/views' => base_path('resources/views/vendor/toastr'),            __DIR__.'/config/toastr.php' => config_path('toastr.php'),        ]);    }    /**     * Register the application services.     *     * @return void     */    public function register()    {        $this->app['toastr'] = $this->app->share(function ($app) {            return new Toastr($app['session'], $app['config']);        });    }    /**     * Get the services provided by the provider.     *     * @return array     */    public function provides()    {        return ['toastr'];    }}
Copy after login

$this->loadViewsFrom(__DIR__ . ‘/views’, ‘Toastr’); 就是表示Toastr命名空间的视图文件冲当前目录的views目录中渲染,所以我们上面用 return view(‘Toastr::toastr’, compact(‘javascript’));

$this->publishes 在执行php artisan vendor:publish 时会将对应的目录和文件复制到对应的位置

10.测试下是否可行,修改 config/app.php 添加如下:

/*    |--------------------------------------------------------------------------    | Class Aliases    |--------------------------------------------------------------------------    |    | This array of class aliases will be registered when this application    | is started. However, feel free to register as many as you wish as    | the aliases are "lazy" loaded so they don't hinder performance.    |    */    'aliases' => [        ......        'Toastr' => Yuansir\Toastr\Facades\Toastr::class,    ],
Copy after login

写个控制器放进去试试:

<?phpnamespace App\Http\Controllers;use App\Http\Requests;use Illuminate\Http\Request;use Toastr;class HomeController extends Controller{    /**     * Create a new controller instance.     *     * @return void     */    public function __construct()    {        //略    }    /**     * Show the application dashboard.     *     * @return \Illuminate\Http\Response     */    public function index(Request $request)    {        Toastr::error('你好啊','标题');        return view('home');    }}
Copy after login




到此结束,大功告成,这样一个Laravel 的 composer 包就开发完成了。 反正我测试是OK了,就不截图了!!

11.修改命名空间到包的composer.json,因为别人安装这个包的时候不可能也去改项目composer.json的PSR-4的autoload,所以我们把PSR-4的命名空间加到这个包的composer.json中去,修改packages/yuansir/toastr/src/composer.json 如下:

{    "name": "ryan/toastr-for-laravel",    "description": "toastr.js for laravel5",    "authors": [        {            "name": "Ryan",            "email": "yuansir@live.cn"        }    ],    "require": {},    "autoload": {        "psr-4": {            "Yuansir\\Toastr\\": "src/"        }    }}
Copy after login

12.建立Github项目


将代码push到项目中去:

$ cd packages/yuansir/toastr/$ git init$ git add .$ git commit -m "add package source files."$ git remote add origin git@github.com:yuansir/toastr-for-laravel5.git$ git push -u origin master$ git tag -a 1.0.0 -m "version 1.0.0"$ git push --tags
Copy after login
13.提交到Packagist,打开到 packagist.org,登陆后点击右边上角的 submit,并填入git的项目地址git@github.com:yuansir/toastr-for-laravel5.git 点击 check 就OK了




到此结束,大功告成,这样一个Laravel 的 composer 包就开发完成了。

这个教程的源码和这个包的安装使用方法详见github https://github.com/yuansir/toastr-for-laravel5

如有问题欢迎指正!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

See all articles