一个门面后面的多个班级

时间:2017-05-23 12:21:21

标签: php laravel singleton facade laravel-facade

门面

namespace App\Webshop\Facades;

use Illuminate\Support\Facades\Facade;

class Webshop extends Facade
{
    /**
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return \App\Webshop\Webshop::class;
    }
}

的ServiceProvider

namespace App\Webshop;

use Illuminate\Support\ServiceProvider;

class WebshopServiceProvider extends ServiceProvider
{
    /**
     * @return void
     */
    public function register()
    {
        $this->app->bind(\App\Webshop\Webshop::class, function() {
            return new Webshop(new Cart(), new Checkout());
        });

        // or

        $this->app->singleton(\App\Webshop\Webshop::class, function() {
            return new Webshop(new Cart(), new Checkout());
        });
    }
}

网上商店

namespace App\Webshop;

class Webshop
{
    /**
     * @var Cart $cart
     */
    private $cart;

    /**
     * @var Checkout $checkout
     */
    private $checkout;

    public function __construct(Cart $cart, Checkout $checkout)
    {
        $this->cart = $cart;
        $this->checkout = $checkout;
    }

    /**
     * @return Cart
     */
    public function cart()
    {
        return $this->cart;
    }

    /**
     * @return Checkout
     */
    public function checkout()
    {
        return $this->checkout;
    }
}

当我跑步时:

Route::get('test1', function () {
    Webshop::cart()->add(1); // Product id
    Webshop::cart()->add(2); // Product id

    dd(Webshop::cart()->totalPrice());
});

它转储" 24.98" (价格计算)

但是当我跑步时:

Route::get('test2', function () {
    dd(Webshop::cart()->totalPrice());
}); 

它显示了我" 0"

我认为问题出在ServiceProvider中,因为当它注册时会创建CartCheckout的新对象

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:-1)

编辑:除了使用单例之外,您的代码永远不会将购物车信息持久存储到会话或数据库中。脚本执行后PHP不会持久化对象。您需要设计购物车以保留信息。

你需要一个单身人士。在服务提供商中将$this->app->bind更改为$this->app->singletonhttp://www.phptherightway.com/pages/Design-Patterns.html

Laravel为您做到这一点,您需要做的就是将其绑定为服务提供商中的单身人士。