正面
namespace App\Webshop\Facades;
use Illuminate\Support\Facades\Facade;
class Webshop extends Facade
{
/**
* @return string
*/
protected static function getFacadeAccessor()
{
return \App\Webshop\Webshop::class;
}
}
服务提供者
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 中,因为当它注册时,它会创建新的对象Cart
和Checkout
我该如何解决这个问题?