Laravel最佳实践

本文持续更新中20190703

本文持续更新中20190630

Route

  • 添加前缀区分命名空间
class RouteServiceProvider extends ServiceProvider
{
    public function map()
    {
        $this->mapApiRoutes();
    }

    protected function mapApiRoutes()
    {
        Route::prefix('api')
             ->middleware('api')
             ->namespace($this->namespace)
             ->group(base_path('routes/api.php'));
    }
}

Eloquent

  • fillable优先级高于guarded
// vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/GuardsAttributes.php
trait GuardsAttributes
{
    /**
     * The attributes that are mass assignable.
     */
    protected $fillable = [];

    /**
     * The attributes that aren't mass assignable.
     */
    protected $guarded = ['*'];
}

Event

// app/Providers/EventServiceProvider.php
class EventServiceProvider extends ServiceProvider
{
    protected $listen = [
        'Illuminate\Auth\Events\Failed' => [
            'App\Listeners\EventListener',
        ],
    ];
}
// app/Listeners/EventListener.php
class EventListener
{
    public function __construct()
    {
        //
    }

    public function handle(Failed $event)
    {
        dd($event);
    }
}

关于更多Event可以参考Laravel 的用户认证系统 / Getting Started with Laravel Model Events

部署

composer install --no-dev

不同于migration, seed只适用于开发环境 => 生成生产数据需要加入到migration

// 配置缓存
php artisan config:cache

// 路由缓存
php artisan route:cache

// 优化autoloader
composer install --optimize-autoloader

参考

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。