Hi,
Im using slim3 with league container. converted project from pimple. Trying to create session basket to add products
Getting error: Alias (App\Basket\Contracts\StorageInterface) is not being managed by the container, must I created a new StorageInterfaceServiceProvider
StorageInterfaceServiceProvider.php
This is my service provider
namespace App\Providers;
use App\Basket\Contracts\StorageInterface;
use App\Basket\SessionStorage;
use League\Container\ServiceProvider\AbstractServiceProvider;
//use League\Container\ServiceProvider\BootableServiceProviderInterface;
use App\Views\View as Twig;
class StorageInterfaceServiceProvider extends AbstractServiceProvider {
protected $provides = [
StorageInterface::class,
];
public function register() {
$container = $this->getContainer();
$container->share(StorageInterface::class, function () use ($container) {
return new SessionStorage
(
'cart',
$container->get(StorageInterface::class)
);
});
}
}
BasketServiceProvider.php
namespace App\Providers;
use App\Basket\Basket;
use App\Basket\Contracts\StorageInterface;
use App\Models\Product;
use League\Container\ServiceProvider\AbstractServiceProvider;
use App\Views\View as Twig;
class BasketServiceProvider extends AbstractServiceProvider {
protected $provides = [
Basket::class,
StorageInterface::class,
Product::class
];
public function register() {
$container = $this->getContainer();
$container->share(Basket::class, function () use ($container) {
return new Basket(
$container->get(StorageInterface::class),
$container->get(Product::class)
);
});
}
}
StorageInterface.php
namespace App\Basket\Contracts;
interface StorageInterface {
public function get($key);
public function set($key, $value);
public function all();
public function exists($key);
public function delete($key);
public function clear();
}
SessionStorage.php
namespace App\Basket;
use Countable;
use App\Basket\Contracts\StorageInterface;
class SessionStorage implements StorageInterface, Countable {
protected $bucket;
public function __construct($bucket = 'default') {
if (!isset($_SESSION[$bucket])) {
$_SESSION[$bucket] = [];
}
$this->bucket = $bucket;
}
public function get($key) {
if (!$this->exists($key)) {
return null;
}
return $_SESSION[$this->bucket][$key];
}
public function set($key, $value) {
$_SESSION[$this->bucket][$key] = $value;
}
public function all() {
return $_SESSION[$this->bucket];
}
public function exists($key) {
return isset($_SESSION[$this->bucket][$key]);
}
public function delete($key) {
if ($this->exists($key)) {
unset($_SESSION[$this->bucket][$key]);
}
}
public function clear() {
unset($_SESSION[$this->bucket]);
}
/**
* Count elements of an object
*
* @link http://php.net/manual/en/countable.count.php
* @return int The custom count as an integer.
* </p>
* <p>
* The return value is cast to an integer.
* @since 5.1.0
*/
public function count() {
return count($this->all());
}
}