嗨,我正在寻找在通用模式中处理精简存储库模式
喜欢:
productRepositoryInterface
productRepository
product
ProducCOntroller
如何使用 SLIM 的依赖注入(inject)来构建它
我有路由,它会转到名为 ProductController 的 Controller
然后在 Controller 中,我想在构造函数中获取 ProductRepo 接口(interface)
我的依赖项
$container['productController'] = function($c , ProductRepositoryInterface $productRepo) use ($app) {
return new ProductController($c ,$productRepo);
};
$container['productsRepository'] = function($c) use ($app) {
return new ProductRepository( $c->db );
};
但是我在 Controller 构造函数中遇到以下错误:
Catchable fatal error: Argument 2 passed to ProductController::__construct() must be an instance of ProductRepositoryInterface, none given
产品 Controller :
function __construct($c,ProductRepositoryInterface $repo)
{
$this->c = $c;
// grab instance from container
$this->repository = $repo;
}
最佳答案
默认情况下 slim 仅将容器对象传递给构造函数。现在您有两个选择。
第一个选项:从容器中获取存储库。
伪代码示例:
注册容器条目:
use App\Service\Product\ProductRepositoryInterface;
use App\Service\Product\ProductRepository;
$container[ProductRepositoryInterface::class] = function (Container $container) {
$db = $container->get('db');
return new ProductRepository($db);
};
创建 Controller :
namespace App\Controller;
use Slim\Container;
use App\Service\Product\ProductRepositoryInterface;
class ProductController
{
/**
* @var ProductRepositoryInterface
*/
private $productRepo;
public function __construct(Container $container)
{
// grab instance from container
$this->productRepo = $container->get(ProductRepositoryInterface::class);
}
}
第二个选项:干净的依赖注入(inject)。为 Controller 创建一个容器条目并直接传递所有依赖项。
use Slim\Container;
use App\Service\Product\ProductRepositoryInterface;
use App\Controller\ProductController;
use App\Service\Product\ProductRepository;
$container[ProductRepositoryInterface::class] = function (Container $container) {
$db = $container->get('db');
return new App\Service\Product\ProductRepository($db);
};
$container[ProductController::class] = function(Container $container)
{
$productRepo = $container->get(ProductRepositoryInterface::class);
return new ProductController($productRepo);
};
Controller
namespace App\Controller;
use Slim\Container;
use App\Service\Product\ProductRepositoryInterface;
class ProductController
{
/**
* @var ProductRepositoryInterface
*/
private $productRepo;
public function __construct(ProductRepositoryInterface $productRepo)
{
$this->productRepo = $productRepo;
}
}
关于php - SLIM 3 中的存储库模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48556446/