扩展资源控制器

Luí*_*ria 2 laravel laravel-4

我正在以某种方式做我想做的事情,而我正在寻找替代方案或更好的方法.我在我的应用程序中使用资源控制器.我也在几个型号中使用softdelete,所以我的路线如下:

Route::get('users/deleted', array('uses' => 'UserController@trash'));
Route::put('users/{id}/restore', array('uses' => 'UserController@restore'));
Route::resource('users', 'UserController');
Run Code Online (Sandbox Code Playgroud)

第一个路径是显示已删除的对象.第二个允许我恢复这些删除的元素.第三种映射传统方法(创建,编辑,更新等).

我有几个控制器以完全相同的方式工作,我想知道是否有任何方法告诉laravel默认使用这两种方法(垃圾和删除)没有两个额外的行.

可能吗?或者提供一个更好的方式,我正在做什么?(抱歉英文不好)

Ant*_*iro 7

保持简单和干燥.

您可以扩展路由器并替换app/config/app.php文件中的Route Facade,但似乎需要做很多工作才能获得更多收益,但不要忘记您的路由文件是PHP脚本,您可以执行以下操作:

$routes = [
    ['users' => 'UserController'],
    ['posts' => 'PostController'],
];

foreach ($routes as $key => $controller)
{
    Route::get("$key/deleted", array('uses' => "$controller@trash"));

    Route::put("$key/{id}/restore", array('uses' => "$controller@restore"));

    Route::resource($key, $controller);
}
Run Code Online (Sandbox Code Playgroud)

扩展路由器

要扩展路由器,您需要创建3个类:

路由器扩展,您将在其中添加新方法:

<?php namespace App\Routing;

class ExtendedRouter extends \Illuminate\Routing\Router {

    protected $resourceDefaults = array(
                'index', 
                'create', 
                'store', 
                'show', 
                'edit', 
                'update', 
                'destroy', 
                'deleted',
                'restore',
    );

    protected function addResourceDeleted($name, $base, $controller)
    {
        $uri = $this->getResourceUri($name).'/deleted';

        return $this->get($uri, $this->getResourceAction($name, $controller, 'deleted'));
    }

    protected function addResourceRestore($name, $base, $controller)
    {
        $uri = $this->getResourceUri($name).'/{resource}/restore';

        return $this->get($uri, $this->getResourceAction($name, $controller, 'restore'));
    }

}
Run Code Online (Sandbox Code Playgroud)

服务提供商,使用Laravel使用的相同IoC标识符('路由器')来引导新路由器:

<?php namespace App\Routing;

use Illuminate\Support\ServiceProvider;

class ExtendedRouterServiceProvider extends ServiceProvider {

    protected $defer = true;

    public function register()
    {
        $this->app['router'] = $this->app->share(function() { return new ExtendedRouter($this->app); });
    }

    public function provides()
    {
        return array('router');
    }

}
Run Code Online (Sandbox Code Playgroud)

还有一个门面,取代Laravel的一个

<?php namespace App\Facades;

use Illuminate\Support\Facades\Facade as IlluminateFacade;

class ExtendedRouteFacade extends IlluminateFacade {

    public static function is($name)
    {
        return static::$app['router']->currentRouteNamed($name);
    }

    public static function uses($action)
    {
        return static::$app['router']->currentRouteUses($action);
    }

    protected static function getFacadeAccessor() { return 'router'; }

}
Run Code Online (Sandbox Code Playgroud)

然后,您需要将您的服务提供商和Facade添加到您的app/config/app.php文件中,评论Laravel原始文件.