Laravel 扩展类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14629083/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel extending class
提问by Alex
Are there any other steps required to extend a class in Laravel 3?
在 Laravel 3 中扩展类还需要其他步骤吗?
I created application/libraries/response.php
:
我创建了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');
}
}
But for some reason, neither the my_test()
function, or the modified json()
function works.
但出于某种原因,该my_test()
函数或修改后的json()
函数都不起作用。
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?
没有工作,我错过了什么?
回答by Laurence
You should add a name space first - like this:
您应该先添加一个命名空间 - 像这样:
file: application/libraries/extended/response.php
文件: 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
然后在 config/application.php 中,您需要更改别名
'Response' => 'Extended\Response',
Then in start.php
然后在 start.php
Autoloader::map(array(
'Extended\Response' => APP_PATH.'libraries/extended/response.php',
));
回答by Alex
Actually, the proper way to extend a library would be the following:
实际上,扩展库的正确方法如下:
- Create
response.php
inapplication/libraries/
- Inside it, extend the class the following way:
class Response extends \Laravel\Response
- Comment
'Response' => 'Laravel\\Response'
inapplication/config/application.php
- 创建
response.php
于application/libraries/
- 在其中,按以下方式扩展类:
class Response extends \Laravel\Response
- 评论
'Response' => 'Laravel\\Response'
在application/config/application.php
Tested and it works. That's how I do it now
经测试,它有效。我现在就是这样做的