laravel¿ØÖÆ·´×ª·´Éä
ÔÚlaravelÖУ¬¿ØÖÆ·´×ªºÍ·´ÉäÊǺÜÊÇÖ÷ÒªµÄ¿´·¨¡£ËüÃÇÊÇlaravel¿ò¼ÜµÄ½¹µãÌØÕ÷£¬Äܹ»ÏÔÖøÌá¸ß´úÂëµÄ¿É¶ÁÐÔ¡¢ÎÞаÐԺͿÉά»¤ÐÔ¡£±¾ÎĽ«ÌÖÂÛ¿ØÖÆ·´×ªºÍ·´ÉäµÄ¿´·¨¡¢Ó÷¨ºÍʵÀý¡£
¿ØÖÆ·´×ª
¿ØÖÆ·´×ª£¨Inversion of Control£¬IoC£©ÊÇÃæÏò¹¤¾ß±à³ÌÖеÄÒ»ÖÖÉè¼Æģʽ£¬ËüÊÇÒ»ÖÖ½«¿ØÖÆȨתÒƸøÁíÒ»¸ö¹¤¾ßµÄ·½·¨£¬ÒÔµÖ´ï½µµÍ´úÂëµÄñîºÏ¶ÈµÄÄ¿µÄ¡£
ÔÚLaravelÖУ¬¿ØÖÆ·´×ªÊÇÖ¸½«ÒÀÀµ¹¤¾ßµÄ½¨ÉèºÍÖÎÀí½»ÓÉÈÝÆ÷À´´¦Öóͷ££¬¶ø²»ÊÇÓɹ¤¾ß×Ô¼º½¨Éè»òÖÎÀíÒÀÀµ¹¤¾ß¡£ÏêϸʵÏÖ·½·¨ÊÇͨ¹ýÒÀÀµ×¢È루Dependency Injection£¬DI£©ºÍЧÀÍÈÝÆ÷£¨Service Container£©¡£
ÒÀÀµ×¢ÈëÊÇָͨ¹ý½á¹¹º¯Êý¡¢ÒªÁì²ÎÊý»òÊôÐÔ£¬×Ô¶¯µØ½«ÒÀÀµ¹¤¾ß×¢Èëµ½ÐèҪʹÓÃËüÃǵŤ¾ßÖС£ÒÀÀµ×¢ÈëʹµÃÿ¸ö¹¤¾ß¶¼¿ÉÒÔרעÓÚ×Ô¼ºµÄÔðÈΣ¬¶ø²»ÐèÒªÌåÌùÒÀÀµ¹¤¾ßµÄ½¨ÉèºÍÖÎÀíÎÊÌâ¡£ÕâÌá¸ßÁË´úÂëµÄ¿É¶ÁÐԺͿÉά»¤ÐÔ¡£
ЧÀÍÈÝÆ÷ÊÇÒ»¸ö¿ÉÉèÖõÄÒÀÀµ×¢ÈëÈÝÆ÷£¬¿ÉÒÔͨ¹ýת´ï²ÎÊý»òÉèÖÃÎļþ£¬ÇáËɵØÖÎÀíÏ¢ÕùÎö¹¤¾ßµÄÒÀÀµ¹Øϵ¡£Ð§ÀÍÈÝÆ÷µÄʹÓÃʹµÃ´úÂëÖеŤ¾ß¿ÉÒÔÔ½·¢ÎÞа¡¢¿ÉÀ©Õ¹ºÍÃæÏòÉèÖá£
·´Éä
·´É䣨Reflection£©ÊÇÖ¸ÔÚ³ÌÐòÕýÔÚÔËÐÐʱ£¬¶¯Ì¬µØ»ñÈ¡ºÍÐ޸Ť¾ßµÄÐÅÏ¢¡¢ÊôÐÔºÍÒªÁì¡£·´Éä¿ÉÒÔÓÃÓÚÖîÈç´úÂëÆÊÎö¡¢²âÊԺ͵÷ÊÔµÈÄ¿µÄ¡£
ÔÚLaravelÖУ¬·´Éä±»ÆÕ±éÓ¦ÓÃÓÚЧÀÍÈÝÆ÷ºÍ·ÓÉÆ÷ÖС£Í¨¹ý·´É䣬¿ÉÒÔ¶¯Ì¬µØÆÊÎöÀàºÍ¹¤¾ßµÄÒÀÀµ¹Øϵ£¬²¢¶ÔËüÃǾÙÐÐʵÀý»¯ºÍŲÓá£ÕâʹµÃLaravel¿ò¼Ü¾ßÓÐÎÞаµÄÉèÖúͿÉÀ©Õ¹ÐÔ£¬¿ÉÒÔͨ¹ý×îСµÄÐÞ¸ÄÀ´Ë³Ó¦²î±ðµÄÐèÇó¡£
ʵÏÖÀý×Ó
ÏÂÃæÊÇÒ»¸ö¼òÆÓµÄʵÏÖÀý×Ó£¬Õ¹Ê¾ÔõÑùʹÓÿØÖÆ·´×ªºÍ·´ÉäÀ´½¨ÉèºÍÖÎÀí¹¤¾ßµÄÒÀÀµ¹Øϵ£º
class UserRepository { protected $db; public function __construct($db) { $this->db = $db; } public function getUsers() { return $this->db->select('users', '*'); } } class UserController { protected $userRepository; public function __construct(UserRepository $userRepository) { $this->userRepository = $userRepository; } public function index() { $users = $this->userRepository->getUsers(); return view('users.index', compact('users')); } } $container = new Container; $container->bind('db', function () { $host = env('DB_HOST'); $user = env('DB_USER'); $pass = env('DB_PASS'); $name = env('DB_NAME'); $db = new Database($host, $user, $pass, $name); return $db; }); $container->bind('userRepository', function ($c) { $db = $c->get('db'); return new UserRepository($db); }); $controller = $container->make('UserController'); $response = $controller->index();
µÇ¼ºó¸´ÖÆ
ÉÏÃæµÄ´úÂëչʾÁËÔõÑùʹÓÃЧÀÍÈÝÆ÷ºÍÒÀÀµ×¢ÈëÀ´ÖÎÀíUserControllerºÍUserRepositoryÖ®¼äµÄÒÀÀµ¹Øϵ¡£ContainerÀàÊÇLaravel¿ò¼ÜÖеÄЧÀÍÈÝÆ÷ʵÏÖ¡£bindÒªÁìÓÃÓÚ×¢²áЧÀͺÍÒÀÀµ¹Øϵ¡£makeÒªÁìÓÃÓÚÆÊÎö¹¤¾ß¼°ÆäÒÀÀµ¹Øϵ¡£
×ܽá
¿ØÖÆ·´×ªºÍ·´ÉäÊÇLaravel¿ò¼ÜÖкÜÊÇÖ÷ÒªµÄ¿´·¨¡£ËüÃÇÄܹ»ÏÔÖøÌá¸ß´úÂëµÄ¿É¶ÁÐÔ¡¢ÎÞаÐԺͿÉά»¤ÐÔ¡£ÔÚʹÓÃLaravel¿ò¼Üʱ£¬Ã÷È·ºÍÓ¦ÓÃÕâЩ¿´·¨ÊǺÜÊÇÖ÷ÒªµÄ¡£ÎÒÃÇÏ£Íû±¾ÎĶÔÄúÓÐËù×ÊÖú£¬½Ó´ýÁôÑÔÌÖÂÛ¡£
ÒÔÉϾÍÊÇlaravel¿ØÖÆ·´×ª·´ÉäµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡