【问题标题】:Laravel extending classLaravel 扩展类
【发布时间】:2013-01-15 17:58:51
【问题描述】:

在 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() 函数都不起作用。

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

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

没有工作,我错过了什么?

【问题讨论】:

    标签: php namespaces extend laravel laravel-3


    【解决方案1】:

    你应该先添加一个命名空间——像这样:

    文件: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 中你需要更改别名

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

    然后在start.php中

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

    【讨论】:

    • 输出返回:Class 'Extended\Response' not found
    • 对不起 - 把文件放在 /application/libraries/extended/response.php
    • 还是..Class 'Extended\Laravel\Response' not found
    • 我对我的帖子进行了编辑以包含一个自动加载器 - 试试吧
    • 好的,非常感谢。但是就没有别的办法了吗?我的意思是,在 CodeIgniter 中是如此简单,但在 Laravel 中你必须经历这一切才能扩展一个类?
    【解决方案2】:

    实际上,扩展库的正确方法如下:

    1. application/libraries/ 中创建response.php
    2. 在其中,通过以下方式扩展类:class Response extends \Laravel\Response
    3. application/config/application.php 中评论'Response' =&gt; 'Laravel\\Response'

    经过测试,它可以工作。我现在就是这样做的

    【讨论】:

      猜你喜欢
      • 2018-06-10
      • 2014-05-18
      • 2016-07-23
      • 1970-01-01
      • 2013-06-08
      • 2015-12-03
      • 2012-12-30
      • 2019-02-18
      • 2014-01-13
      相关资源
      最近更新 更多