Are there any other steps required to extend a class in Laravel 3?
I created 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.
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:
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:
- 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
Tested and it works. That's how I do it now
来源:https://stackoverflow.com/questions/14629083/laravel-extending-class