怎么用PHP特性trait實現(xiàn)簡易LaravelFacade

今天小編給大家分享一下怎么用PHP特性trait實現(xiàn)簡易Laravel Facade的相關(guān)知識點,內(nèi)容詳細,邏輯清晰,相信大部分人都還太了解這方面的知識,所以分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后有所收獲,下面我們一起來了解一下吧。                           

沅江網(wǎng)站建設公司創(chuàng)新互聯(lián)公司,沅江網(wǎng)站設計制作,有大型網(wǎng)站制作公司豐富經(jīng)驗。已為沅江上千家提供企業(yè)網(wǎng)站建設服務。企業(yè)網(wǎng)站搭建\成都外貿(mào)網(wǎng)站建設公司要多少錢,請找那個售后服務好的沅江做網(wǎng)站的公司定做!

簡述

Facade 可以有效幫我實現(xiàn)方法的靜態(tài)化。Laravel 大部分的擴展包都使用了 Facade。
下面的簡易 Facade 主要是利用 PHP 的特性 trait,魔術(shù)方法 __callStatic,反射類 ReflectionClass。

使用場景

后臺系統(tǒng)大部分都會有類似這樣的操作:

<?php
$user = User::find($id);if (!$user) {
    throw new \Expection("資源不存在");}

這樣似乎沒有什么問題,但是還會存在下面這樣的:

$article = Article::find($id);if (!$article) {
    throw new \Expection("資源不存在");}$article->delete();

這樣寫法十分不優(yōu)雅。

上代碼

1、首先我們應該要有一個 Service

<?phpnamespace App\Services;use App\Traits\ModeServiceTrait;class ModelService extends BaseService{
    use ModeServiceTrait;}

2、新建一個 Trait

trait 為了多繼承而存在的,可以去 PHP官網(wǎng) 看文檔。

<?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{
    /**
     * 回調(diào)方法
     *
     * @param Model|null $model
     * @param string $method
     * @return Model
     * @throws ResourceException
     */
    public static function callback(Model|null $model, string $method): Model    {
        switch ($method)
        {
            case 'first':
            case 'find':
                if (!$model) {
                    throw new ResourceException("資源不存在");
                }
                break;

            default:

                break;
        }

        return $model;
    }

    /**
     * 調(diào)用不存在的方法時觸發(fā)
     *
     * @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();

        // 調(diào)用該不存在的方法
        $model = call_user_func_array([$instance, $method], [$arg]);

        // 如果存在復雜操作交給 callback
        return isset($args[2]) ? $args[2]($model) : self::callback($model, $method);
    }}

首先我們關(guān)注 __callStatic 這個魔術(shù)方法。 當調(diào)用不存在的靜態(tài)方法時會觸發(fā)該方法。和他相似的魔術(shù)方法是 __call。這是使用 __callStatic 是為了達到 Facade 的效果。

__callStatic 有兩個回調(diào)參數(shù) $method被調(diào)用的且不存在的方法$args$method 方法中所傳遞的參數(shù)(數(shù)組形式)。

這樣一個簡易的 trait 就完成了。

使用

我們新建一個 command

$ php artisan make:command TestCommand

寫入下面的內(nèi)容

<?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 = 'test:test';

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

    /**
     * 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 模型需要自己去創(chuàng)建。
接下來就可以看看效果了:

$ php artisan test:test

以上就是“怎么用PHP特性trait實現(xiàn)簡易Laravel Facade”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家閱讀完這篇文章都有很大的收獲,小編每天都會為大家更新不同的知識,如果還想學習更多的知識,請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。

網(wǎng)頁名稱:怎么用PHP特性trait實現(xiàn)簡易LaravelFacade
轉(zhuǎn)載來于:http://bm7419.com/article32/goeosc.html

成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供外貿(mào)建站網(wǎng)站內(nèi)鏈、品牌網(wǎng)站制作、服務器托管、ChatGPT

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都做網(wǎng)站