Laravel深入学习12 - 依赖倒置原则
声明:本文并非博主原创,而是来自对《Laravel 4 From Apprentice to Artisan》阅读的翻译和理解,当然也不是原汁原味的翻译,能保证90%的原汁性,另外因为是理解翻译,肯定会有错误的地方,欢迎指正。 欢迎转载,转载请注明出处,谢谢! 依赖反转原则介绍我们来到了SOLID设计原则的最终的目标远景!它就是依赖反转原则,它是指高阶代码不能依赖低阶代码。相应的,高阶代码应该依赖一个抽象层,它是在高阶代码和低阶代码之间的“中间人”角色。另一方面,该原则指代抽象层不依赖具体实现,而是细节依赖抽象。如果这个读起来很晦涩,别担心。我们下面会对这两个方面具体的阐述本原则。
实探如果你已经读过本书之前的章节,就应该对依赖反转有一个很好的理解。我们通过下面例子来解释: class Authenticator { public function __construct(DatabaseConnection $db) { $this->db = $db; } public function findUser($id) { return $this->db->exec('select * from users where id = ?',array($id)); } public function authenticate($credentials) { // Authenticate the user... } } 可以猜到, interface UserProviderInterface { public function find($id); public function findByUsername($username); } 然后,将接口的实现注入到 class Authenticator { public function __construct(UserProviderInterface $users,HasherInterface $hash) { $this->hash = $hash; $this->users = $users; } public function findUser($id) { return $this->users->find($id); } public function authenticate($credentials) { $user = $this->users->findByUsername($credentials['username']); return $this->hash->make($credentials['password']) == $user->password; } } 这些改变之后,我们的 class RedisUserProvider implements UserProviderInterface { public function __construct(RedisConnection $redis) { $this->redis = $redis; } public function find($id) { $this->redis->get('users:'.$id); } public function findByUsername($username) { $id = $this->redis->get('user:id:'.$username); return $this->find($id); } }
在我们将 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |