如何处理不“真实”的依赖关系依赖关系?

发布于 2024-12-02 21:00:55 字数 545 浏览 0 评论 0原文

我有一个“Validator”类,可以对数据数组进行任意检查。例如,检查数组中给定值的字符串长度。验证器还可以检查给定值并查看它在数据库中是否唯一。

我想对这个类进行适当的依赖注入,但是,我正在努力解决如何在这种情况下实现它。验证器不需要需要数据库连接即可运行。所有其他验证检查在没有数据库连接的情况下都可以正常工作。现在,我可以选择使用属性注入来指定连接。或者,如果没有通过属性注入指定连接,我将使用服务定位器模式来解析来自 IoC 容器的默认连接。

我做错了吗?处理类运行不需要的类依赖关系的正确方法是什么?

我目前使用验证器的方式如下:

$rules = array(
    'email'    => 'required|unqiue:users',
    'password' => 'required|confirmed',
);

$validator = new Validator($attributes, $rules);

当然,“唯一”规则告诉验证器检查“用户”表上电子邮件地址的唯一性。

I have a "Validator" class that can do arbitrary checks on an array of data. For instance, check the string length of a given value within the array. The validator can also check a given value and see if it is unique in a database.

I would like to do proper dependency injection on this class, however, I'm struggling with how to implement it in this scenario. The Validator doesn't need a database connection to function. All of the other validation checks work fine without a database connection. Right now, I have the option of specifying the connection using property injection. Or, if no connection is specified via property injection, I'm using the Service Locator pattern to resolve the default connection from the IoC container.

Am I doing it wrong? What is the proper way to handle class dependencies that aren't required for the class to function?

I currently consume the validator like so:

$rules = array(
    'email'    => 'required|unqiue:users',
    'password' => 'required|confirmed',
);

$validator = new Validator($attributes, $rules);

Of course, the "unique" rule tells the validator to check the uniqueness of the e-mail address on the "users" table.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一场春暖 2024-12-09 21:00:55

使用接口或抽象类仅加载当前情况的正确实现。就我个人而言,我几乎从未需要使用它们中的任何一个,但它们是专门为解决依赖性问题而设计的。

Make use of interfaces or abstract classes to load only the proper implementation for the current case. Personally, I've almost never had the need to use either of them, but they are designed specifically for solving dependancy problems.

无所谓啦 2024-12-09 21:00:55

不知道您的问题是否有正确(或接近正确)的答案,但就是这样。

正如您在问题中指出的,由于您的验证器确实需要数据库连接,也就是说您不依赖注入实例的实现来“做一些工作”,那么您可能不需要实现DI。

您可能根本不需要它,只需要将数据库连接处理程序或对数据库访问层的引用传递给需要它的方法。当然,这可能需要对您的代码进行一些更改。

Don't know if there is a right (or close to being right) answer to your question but here it goes.

As you noted in your question, since your validator does require a database connection, that is you don't rely on the implementation of an injected instance to 'do some work' then you might not require to implement DI.

You might not need it after all and only need to pass your DB Connection Handler or Reference to your database access layer to the method that needs it. This might require some changes in your code of course.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文