如何在Laravel中从控制器返回Eloquent Model后扩展默认响应行为?

时间:2014-07-26 13:26:54

标签: laravel laravel-4

我有一个简单的控制器,它从数据库中取出用户并将滔滔不绝的对象返回给用户。

class UsersController extends \BaseController {

    public function show($id)
    {
        $user = User::find($id);

        return $user;
    }

}

默认情况下,Laravel返回JSON。我想返回RJSON,所以我创建了以下宏

Response::macro('rjson', function($collection)
{
    if($collection instanceof Illuminate\Database\Eloquent\Collection)
    {
        $collection = $collection->toArray();
    }

    $collection = Dmitrirussu\RJson::pack($collection);
    return \Response::make($collection);
});

它工作正常,但不方便。我想与控制器中的return $user做出相同的行为。我尝试在json Facade中扩展Respone方法而没有奖励效果。我怎么能做到这一点?

2 个答案:

答案 0 :(得分:3)

我打算在这里提出一个解决方案。这里的免责声明我没有测试过代码,但是这个方法与我在接下来几天要实现的方法非常类似(为Ember.js兼容性重新排列Eloquent结果)。

基本上Taylor Otwell (creator of Laravel) suggested是什么:

  

查看Eloquent \ Model类中的“newCollection”方法。在基本模型中覆盖它并返回扩展Illuminate \ Database \ Eloquent \ Collection的自定义集合。然后在该Collection扩展中覆盖toArray方法以格式化你想要的东西。

所以理论上你可以做这三个步骤:

  1. 创建Illuminate\Database\Eloquent\Collection的子类,并在返回之前覆盖toArray()以执行RJSON格式设置。我们称之为RJsonCollection
  2. 创建Illuminate\Database\Eloquent\Model的子类以覆盖newCollection()方法以使用新的RJsonCollection子类。我们称之为BaseModel
  3. 转换模型以扩展新的BaseModel
  4. 这样的事情:

    应用/模型/ RJsonCollection.php:

    <?php
    
    class RJsonCollection extends Illuminate\Database\Eloquent\Collection
    {
        public function toArray()
        {
            $parentArray = parent::toArray();
    
            return Dmitrirussu\RJson::pack($parentArray);
        }
    }
    

    请注意,我假设根据您的问题代码Dmitrirussu\RJson::pack($parentArray)将返回一个集合/数组。您可能需要调整上面的代码并确保它返回正确的RJSON数组。

    应用/模型/ BaseModel.php:

    <?php
    
    class BaseModel extends Eloquent
    {
        public function newCollection(array $models = array())
        {
            return new RJsonCollection($models);
        }
    }
    

    应用/模型/ UserModel.php:

    <?php
    
    class UserModel extends BaseModel
    {
        // ...
    }
    

    当然,在创建新类时通常使用composer dump-autoload和其他内容。您可能会注意到我将上面的所有类放在models文件夹中,而没有命名空间。不是最佳实践,但它们确实有助于保持示例简单明了。

答案 1 :(得分:0)

您可能还希望将Fractal的变形金刚视为一种以更通用的方式为您的数据创建可重用转换的方法:

http://fractal.thephpleague.com/transformers/