Laravel5 扩展门面

Laravel5 extend Facade

我想扩展 Laravel5 Cookies 功能。 我想这样做: 我将创建文件 App\Support\Facades\Cookie.php,然后创建文件 App\Libraries\CookieJar.php。在 app.php 中,我将 Cookie 的行更改为:

'Cookie' => 'App\Support\Facades\Cookie',

无论如何,当我尝试这样使用它时:

Cookie::test()

它returns:

Call to undefined method 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';
    }

}

class 与您所有的新 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';
    }
}

现在bing它在容器中:

$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')

希望对您有所帮助。