1

我想扩展 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';
    }

}
4

1 回答 1

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

我希望这有帮助。

于 2016-07-22T05:41:54.477 回答