Laravel扩展类 [英] Laravel extending class

查看:87
本文介绍了Laravel扩展类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Laravel 3中扩展类是否还需要其他步骤吗?

Are there any other steps required to extend a class in Laravel 3?

我创建了application/libraries/response.php:

class Response extends Laravel\Response {

    public static function json($data, $status = 200, $headers = array(), $json_options = 0)
    {
        $headers['Content-Type'] = 'application/json; charset=utf-8';

        if(isset($data['error']))
        {
            $status = 400;
        }

        dd($data);

        return new static(json_encode($data, $json_options), $status, $headers);
    }

    public static function my_test()
    {
        return var_dump('expression');
    }

}

但是由于某些原因,my_test()函数或修改后的json()函数都不起作用.

But for some reason, neither the my_test() function, or the modified json() function works.

在我的控制器中,我执行以下操作:

In my controller, I do the following:

Response::my_test();
// or
$response['error']['type']    = 'existing_user';
Response::json($response);

没有任何作用,我想念什么?

And none work, what am I missing?

推荐答案

您应该首先添加一个名称空间-像这样:

You should add a name space first - like this:

文件:application/libraries/extended/response.php

<?php namespace Extended;

class Response extends \Laravel\Response {

  public static function json($data, $status = 200, $headers = array(), $json_options = 0)
  {
    $headers['Content-Type'] = 'application/json; charset=utf-8';

    if(isset($data['error']))
    {
        $status = 400;
    }

    dd($data);

    return new static(json_encode($data, $json_options), $status, $headers);
  }

  public static function my_test()
  {
    return var_dump('expression');
  }
}

然后在config/application.php中,您需要更改别名

Then inside config/application.php you need to change the alias

 'Response'     => 'Extended\\Response',

然后在start.php中

Then in start.php

Autoloader::map(array(
    'Extended\\Response' => APP_PATH.'libraries/extended/response.php',
));

这篇关于Laravel扩展类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆