laravelÒÀÀµ×¢ÈëµÄ¼¸ÖÖʹÓÃÒªÁìºÍÓŵã
laravelÊÇÒ»¸öÊ¢ÐеÄphp¿ò¼Ü£¬ËüÌṩÁËÐí¶à»ù±¾¹¦Ð§À´¼ÓËÙweb¿ª·¢£¬²¢ÇÒʹÓÃÁËÐí¶àÏÖ´úÉè¼Æģʽ£¬Ê¹µÃ´úÂë¸üÒ×ÓÚά»¤ºÍÀ©Õ¹¡£ÆäÖÐÒ»¸ö×îÖ÷ÒªµÄÌØÕ÷ÊÇÒÀÀµ×¢Èë¡£
ÒÀÀµ×¢ÈëÊÇÒ»ÖÖÉè¼Æģʽ£¬Í¨¹ýÕâÖÖģʽ£¬Ò»¸ö¹¤¾ß¿ÉÒÔ¸æËßÁíÒ»¸ö¹¤¾ßËüËùÒÀÀµµÄ¹¤¾ß¡£ÒÀÀµ×¢Èë¿ÉÒÔ´ó´óÌá¸ß´úÂëµÄ¿É²âÊÔÐÔ¡¢¿Éά»¤ÐԺͿÉÀ©Õ¹ÐÔ£¬ÓÉÓÚËü¿ÉÒÔ½«¹¤¾ßÖ®¼äϸÃÜñîºÏµÄ¹Øϵ½âñî¡£
LaravelµÄÒÀÀµ×¢ÈëϵͳÊÇ»ùÓÚIoCÈÝÆ÷£¨¿ØÖÆ·´×ªÈÝÆ÷£©ÊµÏֵġ£IoCÈÝÆ÷ÊÇÒ»¸ö¹¤¾ß£¬Ëü¿ÉÒÔ´¦Öóͷ£¹¤¾ßÖ®¼äµÄÒÀÀµ¹Øϵ£¬²¢ÇÒÔÚÐèÒªµÄʱ¼ä×Ô¶¯µØʵÀý»¯¹¤¾ß¡£LaravelµÄIoCÈÝÆ÷³ÆΪService Container£¨Ð§ÀÍÈÝÆ÷£©£¬Ð§ÀÍÈÝÆ÷ÄÚ²¿Î¬»¤Á˹¤¾ßÖ®¼äµÄÒÀÀµ¹Øϵ£¬²¢Äܹ»×Ô¶¯µØÆÊÎö¹¤¾ßÖ®¼äµÄÒÀÀµ¹Øϵ¡£
ÔÚLaravelÖУ¬ÎÒÃÇ¿ÉÒÔͨ¹ý½á¹¹º¯Êý×¢Èë¡¢ÒªÁì×¢ÈëºÍÊôÐÔ×¢È뽫ÒÀÀµÏî×¢Èëµ½×ðÁú¿Ê±´úÂëÖС£ÏÂÃ潫ÏêϸÏÈÈÝÕ⼸ÖÖÒÀÀµ×¢Èë·½·¨µÄʹÓÃÒªÁìºÍÓŵ㡣
1.½á¹¹º¯Êý×¢Èë
½á¹¹º¯Êý×¢ÈëÊÇ×î³£ÓõÄÒÀÀµ×¢Èë·½·¨£¬Ò²ÊÇ×î¾ß¿É¶ÁÐԵķ½·¨¡£Í¨¹ý½á¹¹º¯Êý×¢È룬ÎÒÃÇ¿ÉÒÔ½«ÒÀÀµÏî×÷Ϊ½á¹¹º¯Êý²ÎÊýת´ï¸øÀàµÄʵÀý¡£ÀýÈ磺
class UserController { protected $userService; public function __construct(UserService $userService) { $this->userService = $userService; } public function getUser($id) { $user = $this->userService->getUserById($id); return view('user', ['user' => $user]); } }
µÇ¼ºó¸´ÖÆ
ÔÚÕâ¸öÀý×ÓÖУ¬ÎÒÃǽ«UserServiceÀà×÷Ϊ½á¹¹º¯Êý²ÎÊýת´ï¸øUserControllerÀà¡£ÕâÑù£¬ÎÒÃÇ¿ÉÒÔÔÚUserControllerÖÐʹÓÃUserServiceʵÀýµÄËùÓÐÒªÁì¡£
Óŵ㣺
ÒÀÀµÏîÃ÷È·£¬Ò×ÓÚÃ÷È·ºÍά»¤¡£
½«ÒÀÀµÏî×¢Èëµ½½á¹¹º¯ÊýÖпÉÒÔʹ´úÂë¸üÒ×ÓÚ²âÊÔ¡£
2.ÒªÁì×¢Èë
ÒªÁì×¢ÈëÊÇÒ»ÖÖ²»ÄÇô³£ÓõÄÒÀÀµ×¢Èë·½·¨¡£Í¨¹ýÒªÁì×¢È룬ÎÒÃÇ¿ÉÒÔ½«ÒÀÀµÏî×÷ΪҪÁì²ÎÊýת´ï¸øÒªÁì¡£ÀýÈ磺
class UserController { protected $userService; public function setUserService(UserService $userService) { $this->userService = $userService; } public function getUser($id) { $this->setUserService(new UserService()); $user = $this->userService->getUserById($id); return view('user', ['user' => $user]); } }
µÇ¼ºó¸´ÖÆ
ÔÚÕâ¸öÀý×ÓÖУ¬ÎÒÃǽ«UserServiceÀà×÷ΪsetUserServiceÒªÁìµÄ²ÎÊýת´ï¸øUserControllerÀà¡£ÕâÑù£¬ÎÒÃÇ¿ÉÒÔÔÚgetUserÒªÁìÖÐʹÓÃUserServiceʵÀýµÄËùÓÐÒªÁì¡£
Óŵ㣺
ÒªÁì×¢Èë¿ÉÒÔ½«ÒÀÀµÏîµÄÉúÃüÖÜÆÚÓëÒªÁìµÄÉúÃüÖÜÆÚÊèÉ¢¿ªÀ´¡£
¿ÉÒÔ¶¯Ì¬µØ×¢ÈëÒÀÀµÏʹµÃ´úÂëÔ½·¢ÎÞа¡£
3.ÊôÐÔ×¢Èë
ÊôÐÔ×¢ÈëÊÇÒ»ÖÖ²»½¨ÒéʹÓõÄÒÀÀµ×¢Èë·½·¨¡£Í¨¹ýÊôÐÔ×¢È룬ÎÒÃǽ«ÒÀÀµÏî×÷ΪÀàµÄÊôÐÔ£¬È»ºóÖ±½Ó»á¼ûÕâ¸öÊôÐÔÀ´Ê¹ÓÃÒÀÀµÏî¡£ÀýÈ磺
class UserController { protected $userService; public function getUser($id) { $this->userService = new UserService(); $user = $this->userService->getUserById($id); return view('user', ['user' => $user]); } }
µÇ¼ºó¸´ÖÆ
ÔÚÕâ¸öÀý×ÓÖУ¬ÎÒÃǽ«UserServiceÀà×÷Ϊ$userServiceÊôÐÔ£¬È»ºóÔÚgetUserÒªÁìÖÐÖ±½Ó½¨ÉèÁËÒ»¸öUserServiceʵÀý²¢¸³Öµ¸ø$userServiceÊôÐÔ¡£
Óŵ㣺
´úÂëÔ½·¢¾«Á·¡£
¿ÉÊÇ£¬ÊôÐÔ×¢ÈëÒ²ÓÐһЩÈõµã£º
Òþ²ØÁËÒÀÀµ¹Øϵ£¬Ê¹µÃ´úÂëÔ½·¢ÄÑÒÔά»¤ºÍµ÷ÊÔ¡£
½ûÖ¹ÒײâÊÔ£¬ÓÉÓÚÄÑÒÔÓÃÄ£Ä⹤¾ßÌæ»»ÏÖʵ¹¤¾ß¡£
×ÛÉÏËùÊö£¬ÒÀÀµ×¢ÈëÊÇÒ»ÖÖºÜÊÇÖ÷ÒªµÄÉè¼Æģʽ£¬¿ÉÒÔʹ×ðÁú¿Ê±´úÂëÔ½·¢¿Éά»¤¡¢¿ÉÀ©Õ¹ºÍÒ×ÓÚ²âÊÔ¡£ÔÚLaravelÖУ¬ÎÒÃÇ¿ÉÒÔʹÓýṹº¯Êý×¢Èë¡¢ÒªÁì×¢ÈëºÍÊôÐÔ×¢ÈëµÈ¶àÖÖ·½·¨½«ÒÀÀµÏî×¢Èëµ½×ðÁú¿Ê±´úÂëÖС£¿ÉÊÇ£¬×îºÃ×èֹʹÓÃÊôÐÔ×¢È룬ÓÉÓÚËü»áÒþ²ØÒÀÀµ¹Øϵ£¬Ê¹µÃ´úÂëÔ½·¢ÄÑÒÔά»¤ºÍµ÷ÊÔ¡£
ÒÔÉϾÍÊÇlaravelÒÀÀµ×¢ÈëµÄ¼¸ÖÖʹÓÃÒªÁìºÍÓŵãµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡