php - SLIM 3 中的存储库模式

标签 php slim slim-3

嗨,我正在寻找在通用模式中处理精简存储库模式

喜欢:

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/

相关文章:

php - PHP环境下的sqlrelay框架,web和cli不一致

php - 注销按钮将用户重定向到同一页面,而不是将用户注销

php - Slim 框架的身份验证不起作用

php - 使用命名空间时无法使用 require_once 加载类

php - Slim 3 中间件重定向

php - 使用 slim-jwt-auth 生成 token

PHP 同时写入文件

php - 防止使用 Slim Framework 访问 'index.php'

php - 为什么所有 Slim 路由都会在加载/启动时初始化?

c# - 如何正确地将 PHP 和 CURL 帖子转换为 groupon API 的 C# HTTP 客户端帖子