我想扩展Laravel5 Cookies功能。 我想这样做: 我将创建文件App \ Support \ Facades \ Cookie.php,而不是文件App \ Libraries \ CookieJar.php。在app.php中,我将Cookie的行更改为:
'Cookie' => 'App\Support\Facades\Cookie',
无论如何,当我尝试使用它时:
Cookie::test()
它返回:
调用未定义的方法Illuminate \ Cookie \ CookieJar :: test()
你有什么想法,为什么这样做?是这样的,我想如何扩展Cookie功能呢?
感谢您的帮助。
以下是文件内容: Cookie.php:
<?php namespace App\Support\Facades;
/**
* @see \App\Libraries\CookieJar
*/
class Cookie extends \Illuminate\Support\Facades\Facade
{
/**
* Determine if a cookie exists on the request.
*
* @param string $key
* @return bool
*/
public static function has($key)
{
return !is_null(static::$app['request']->cookie($key, null));
}
/**
* Retrieve a cookie from the request.
*
* @param string $key
* @param mixed $default
* @return string
*/
public static function get($key = null, $default = null)
{
return static::$app['request']->cookie($key, $default);
}
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'cookie';
}
}
CookieJar.php:
<?php namespace App\Libraries;
class CookieJar extends \Illuminate\Cookie\CookieJar
{
public function test() {
return 'shit';
}
}
答案 0 :(得分:1)
包含所有新Cookie功能的类需要扩展Illuminate\CookieJar\CookieJar
<?php
namespace App\Support\Cookie;
class CookieJar extends \Illuminate\Cookie\CookieJar
{
/**
* Determine if a cookie exists on the request.
*
* @param string $key
* @return bool
*/
public static function has($key)
{
return !is_null(static::$app['request']->cookie($key, null));
}
/**
* Retrieve a cookie from the request.
*
* @param string $key
* @param mixed $default
* @return string
*/
public static function get($key = null, $default = null)
{
return static::$app['request']->cookie($key, $default);
}
}
然后换个新面孔:
namespace App\Support\Facades;
class CookieFacade extends \Illuminate\Support\Facades\Facade
{
protected static function getFacadeAccessor()
{
/*
* You can't call it cookie or else it will clash with
* the original cookie class in the container.
*/
return 'NewCookie';
}
}
现在把它放在容器中:
$this->app->bind("NewCookie", function() {
$this->app->make("App\\Support\\Cookie\\CookieJar");
});
最后在你的app.php配置中添加别名:
'NewCookie' => App\Support\Facades\CookieFacade::class
现在您可以使用NewCookie::get('cookie')
和NewCookie::has('cookie')
。
我希望这会有所帮助。