美文网首页
laravel 5.5 以上使用laracasts/presen

laravel 5.5 以上使用laracasts/presen

作者: charmingcheng | 来源:发表于2020-10-28 11:20 被阅读0次

composer 安装

composer require laracasts/presenter

生成一个presenter命令

php artisan make:command MakePresenter

该命令会在app/console/Commands目录下生成一个MakePresenter.php文件

自定义命令

app/console/Commands/MakePresenter.php

<?php

namespace App\Console\Commands;

use Illuminate\Console\GeneratorCommand;

class MakePresenter extends GeneratorCommand
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'make:presenter';
    
    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create a new presenter class';
    
    /**
     * The type of class being generated.
     *
     * @var string
     */
    protected $type = 'Presenters';
    
    /**
     * Get the stub file for the generator.
     *
     * @return string
     */
    protected function getStub()
    {
        return __DIR__.'\Stubs\presenter.stub';
    }
    
    /**
     * Get the default namespace for the class.
     *
     * @param  string  $rootNamespace
     * @return string
     */
    protected function getDefaultNamespace($rootNamespace)
    {
        return $rootNamespace."\Presenters";
    }
}

自定义一个presenter模板

app/console/Commands/Stubs/presenter.stub

<?php

namespace DummyNamespace;

use Laracasts\Presenter\Presenter;

class DummyClass extends Presenter
{

}

执行命令

php artisan make:presenter CategoryPresenter

运行成功后,会在app/Presenters目录下生成CategoryPresenter.php文件

app/Presenters/CategoryPresenter.php

<?php

namespace App\Presenters;

use Laracasts\Presenter\Presenter;

class CategoryPresenter extends Presenter
{
    // 自定义方法
    public function fullName()
    {
       return $this->firstName.' · '.$this->lastName
    }
}

使用

model 中引入

app/Models/Category

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Laracasts\Presenter\PresentableTrait;  // 引入PresentableTrait

class Category extends Model
{
    use PresentableTrait;

    protected $presenter = 'App\Presenters\CategoryPresenter';  // 绑定presenter
    
    protected $guarded = [];
}

blade页面上使用

{!! $category->present()->fullName !!}

相关文章

网友评论

      本文标题:laravel 5.5 以上使用laracasts/presen

      本文链接:https://www.haomeiwen.com/subject/kiyqvktx.html