【问题标题】:How to extends a facade in laravel?如何在 laravel 中扩展立面?
【发布时间】:2013-06-06 03:58:30
【问题描述】:

我正在尝试在 laravel 4 中扩展一个 facede,但在尝试调用方法时我只收到下一个错误。

Non-static method App\Libraries\Theme::setActive() should not be called statically

编辑

@Antonio 响应后,将方法更改为静态,让使用关键字 $this-> 在方法内部的威力。

Symfony\Component\Debug\Exception\FatalErrorException 使用 $this 当不在 $active = $this->ensureRegistered($active); 的对象上下文中时

我的代码:

<?php namespace App\Libraries;

use Cartalyst\Themes\Facades\Theme as ThemeBag;

class Theme extends ThemeBag {

    /**
     * Sets the active theme.
     *
     * @param  mixed  $active
     * @return Cartalyst\Themes\ThemeInterface
     */
public static function setActive($active)
{
    $active = $this->ensureRegistered($active);

    if ( ! isset($this->themes[$active->getSlug()]))
    {
        $this->register($active);
    }

    $this->active = $active;

    include $this->getActive()->getPath() . '\\helpers\\composers.php';
}
}

【问题讨论】:

    标签: php laravel laravel-4


    【解决方案1】:

    基本上,您必须扩展现有的 Facade:

    <?php namespace AntonioRibeiro\Libraries;
    
    class MyEventFacade extends Illuminate\Support\Facades\Event {
    
        /**
         * Sets the active theme.
         *
         * @param  mixed  $active
         * @return Cartalyst\Themes\ThemeInterface
         */
        public static function setActive($active)
        {
            /// do what you have to do
        }
    
    }
    

    然后将其替换(或添加为新的)到您的 app/config/app.php:

    'aliases' => array(
    
            'App'             => 'Illuminate\Support\Facades\App',
                    ...
         // 'Event'           => 'Illuminate\Support\Facades\Event',
            'Event'      => 'AntonioRibeiro\Libraries\MyEventFacade',
                    ...
            'File'            => 'Illuminate\Support\Facades\File',
            'ActiveSession'   => 'AntonioRibeiro\Facades\ActiveSessionFacade',
    
    ),
    

    别忘了执行“composer dump-autoload”。

    我无权访问这些 Cartalyst 主题,但您收到的错误与您未创建为静态的方法有关:

    public function setActive($active)
    {
    }
    

    应该是

    public static function setActive($active)
    {
    }
    

    你会在这里找到一些关于它的好信息(创建一个扩展请求“外观”的类):http://fideloper.com/extend-request-response-laravel

    【讨论】:

    • 你应该总结一下@Antonio的要点,然后参考文章。
    • 感谢您的回复。要将方法更改为静态,请在方法内部使用关键字 $this。
    猜你喜欢
    • 1970-01-01
    • 2016-07-17
    • 2012-12-14
    • 2019-03-16
    • 2014-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多