登录  /  注册
首页 > php框架 > Laravel > 正文

用PHP特性trait实现简易Laravel Facade

藏色散人
发布: 2022-01-27 16:33:01
转载
1808人浏览过

下面由laravel教程栏目给大家介绍如何利用php trait实现简易facade,希望对大家有所帮助!

简述

Facade 可以有效帮我实现方法的静态化。Laravel 大部分的扩展包都使用了 Facade。【推荐:laravel视频教程
下面的简易 Facade 主要是利用 PHP 的特性 trait,魔术方法 __callStatic,反射类 ReflectionClass。

使用场景

后台系统大部分都会有类似这样的操作:

<?php $user = User::find($id);if (!$user) {
    throw new \Expection("资源不存在");}
登录后复制

这样似乎没有什么问题,但是还会存在下面这样的:

$article = Article::find($id);if (!$article) {
    throw new \Expection("资源不存在");}$article-&gt;delete();
登录后复制

这样写法十分不优雅。

上代码

1、首先我们应该要有一个 Service

<?phpnamespace  App\Services;use App\Traits\ModeServiceTrait;class ModelService extends BaseService{
    use ModeServiceTrait;}
登录后复制

2、新建一个 Trait

trait 为了多继承而存在的,可以去 PHP官网 看文档。

<?php namespace App\Traits;
use \ReflectionClass;
use \Exception;use \ReflectionException;
use Illuminate\Database\Eloquent\Model;
use App\Exceptions\ResourceException;
/**
 * @method static Model find(string $className, int $id, callable $callback = null)
 *
 * @see Model
 * @package App\Services
 */trait ModeServiceTrait{
    /**
     * 回调方法
     *
     * @param Model|null $model
     * @param string $method
     * @return Model
     * @throws ResourceException
     */
    public static function callback(Model|null $model, string $method): Model    {
        switch ($method)
        {
            case &#39;first&#39;:
            case &#39;find&#39;:
                if (!$model) {
                    throw new ResourceException("资源不存在");
                }
                break;

            default:

                break;
        }

        return $model;
    }

    /**
     * 调用不存在的方法时触发
     *
     * @param $method
     * @param $args
     * @return false|mixed
     * @throws ReflectionException
     * @throws ResourceException
     * @throws Exception
     */
    public static function __callStatic($method, $args)
    {
        $className = $args[0];
        $arg = $args[1];

        // 判断模型类是否存在
        if (!class_exists($className)) {
            throw new Exception("The class {$className} could not be found. from:" . __CLASS__);
        }

        // 利用反射实例化其类
        $reflection = new ReflectionClass($className);
        $instance = $reflection->newInstanceArgs();

        // 调用该不存在的方法
        $model = call_user_func_array([$instance, $method], [$arg]);

        // 如果存在复杂操作交给 callback
        return isset($args[2]) ? $args[2]($model) : self::callback($model, $method);
    }}
登录后复制

首先我们关注 __callStatic 这个魔术方法。 当调用不存在的静态方法时会触发该方法。和他相似的魔术方法是 __call。这是使用 __callStatic 是为了达到 Facade 的效果。

__callStatic 有两个回调参数 $method 是 被调用的且不存在的方法,$args 是 $method 方法中所传递的参数(数组形式)。

这样一个简易的 trait 就完成了。

使用

我们新建一个 command

$ php artisan make:command TestCommand
登录后复制

写入下面的内容

<?php namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Services\ModelService;
use App\Models\Article\Article;
class TestCommand extends Command{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = &#39;test:test&#39;;

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = &#39;a test&#39;;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $article = ModelService::find(Article::class, 1);

        $article = ModelService::find(Article::class, 1, function ($model) {
            return $model->load('author');
        });
    }}
登录后复制

其中的 Article 模型需要自己去创建。
接下来就可以看看效果了:

$ php artisan test:test
登录后复制

结语

这样我们就抛弃了使用 abstract 抽象类,来达到了跟 Facade 一样的效果。同时也做到了代码复用。
这样使用程序会多走很多步,但是跟优雅比起来,性能什么的都无所谓了。

表达不是很清楚,需要自己深入体会了。                                                 

以上就是用PHP特性trait实现简易Laravel Facade的详细内容,更多请关注php中文网其它相关文章!

智能AI问答
PHP中文网智能助手能迅速回答你的编程问题,提供实时的代码和解决方案,帮助你解决各种难题。不仅如此,它还能提供编程资源和学习指导,帮助你快速提升编程技能。无论你是初学者还是专业人士,AI智能助手都能成为你的可靠助手,助力你在编程领域取得更大的成就。
相关标签:
来源:learnku网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
最新问题
关于CSS思维导图的课件在哪? 课件
凡人来自于2024-04-16 10:10:18
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 //m.sbmmt.com/ All Rights Reserved | php.cn | 湘ICP备2023035733号