Laravel extending class

别说谁变了你拦得住时间么 提交于 2019-12-04 19:40:24

You should add a name space first - like this:

file: 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');
  }
}

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

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

Then in start.php

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

Actually, the proper way to extend a library would be the following:

  1. Create response.php in application/libraries/
  2. Inside it, extend the class the following way: class Response extends \Laravel\Response
  3. Comment 'Response' => 'Laravel\\Response' in application/config/application.php

Tested and it works. That's how I do it now

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!