ThinkPHP6ÖÐÔõÑùʹÓÃIocÈÝÆ÷ʵÏÖÒÀÀµ×¢È룿
ÔÚÏÖ´úµÄphp¿ª·¢ÖУ¬ÒÀÀµ×¢ÈëÊÇÒ»Ïî²»¿É»òȱµÄÊÖÒÕ¡£ËüÔÊÐíÎÒÃǸüÇáËɵØÖÎÀí´úÂëµÄÖØƯºó£¬²¢Ôö½ø´úÂëÖØÓúͿÉά»¤ÐÔ¡£¶øthinkphp6×÷Ϊһ¿îÊ¢ÐеÄphp¿ò¼Ü£¬Ò²ÌṩÁËÒ»ÖÖÇáÓ¯µÄ·½·¨À´ÊµÏÖÒÀÀµ×¢È롪¡ªiocÈÝÆ÷¡£
IocÈÝÆ÷¼´Inversion of Control(Container)£¬ËüÊÇÒ»¸öͨÓõŤ³§Ä£Ê½£¬ÓÃÓÚʵÏÖ¹¤¾ßµÄÒÀÀµ×¢È롣ͨ¹ýIocÈÝÆ÷£¬ÎÒÃÇ¿ÉÒÔ½«¹¤¾ßµÄ½¨ÉèºÍ¹¤¾ßµÄÒÀÀµ×¢ÈëÊèÉ¢¿ªÀ´¡£ÔÚThinkPHP6ÖУ¬IocÈÝÆ÷±»¼¯³ÉÔÚ¿ò¼ÜµÄ½¹µã×é¼þÖУ¬²¢ÇÒ¿ÉÒÔÔÚÕû¸öÓ¦ÓóÌÐòÖÐʹÓá£
ÄÇô£¬ÔõÑùʹÓÃThinkPHP6ÖеÄIocÈÝÆ÷ʵÏÖÒÀÀµ×¢ÈëÄØ£¿ÏÂÃæÎÒÃǽ«Ïêϸ½â˵¡£
°ì·¨1£º½¨ÉèÐèҪʵÀý»¯µÄÀà
Ê×ÏÈ£¬ÎÒÃÇÐèÒª½¨ÉèÒ»¸öÐèҪʵÀý»¯µÄÀ࣬ÔÚ¸ÃÀàÖнç˵ÐèҪעÈëµÄÒÀÀµ¡£×÷ΪʾÀý£¬ÕâÀïÎÒÃǽ¨ÉèÒ»¸öUserServiceÀ࣬²¢Ôڽṹº¯ÊýÖÐ×¢ÈëÒ»¸öUserRepositoryÀàµÄʵÀý¡£
Á¬Ã¦Ñ§Ï°¡°PHPÃâ·ÑѧϰÌõ¼Ç£¨ÉîÈ룩¡±£»
namespace appservice; use appepositoryUserRepository; class UserService { protected $userRepository; public function __construct(UserRepository $userRepository) { $this->userRepository = $userRepository; } public function getUserList() { return $this->userRepository->getList(); } }
µÇ¼ºó¸´ÖÆ
°ì·¨2£º½¨ÉèÒÀÀµµÄÀà
½ÓÏÂÀ´£¬ÎÒÃÇÐèÒªÏȽ¨ÉèÒÀÀµµÄÀàUserRepository¡£ÔÚʾÀýÖУ¬ÎÒÃǼòÆӵؽç˵һ¸ö·µ»ØËùÓÐÓû§ÁбíµÄgetListÒªÁì¡£
namespace appepository; class UserRepository { public function getList() { return ['user1', 'user2', 'user3']; } }
µÇ¼ºó¸´ÖÆ
°ì·¨3£ºÉèÖÃIocÈÝÆ÷
ÏÖÔÚ£¬ÎÒÃÇÐèÒªÔÚÓ¦ÓóÌÐòµÄÉèÖÃÎļþÖÐÉèÖÃIocÈÝÆ÷¡£ÔÚThinkPHP6ÖУ¬ÉèÖÃÎļþλÓÚconfigĿ¼Ï£¬½¨ÒéÎÒÃǽ¨ÉèÒ»¸öеÄcontainer.phpÉèÖÃÎļþ¡£
ÔÚ¸ÃÉèÖÃÎļþÖУ¬ÎÒÃÇÐèҪע²áÐèҪʵÀý»¯µÄÀàºÍÆäÒÀÀµµÄÀ࣬ÒÔ±ãÓÚIocÈÝÆ÷Äܹ»×¼È·µØ×¢ÈëÒÀÀµ¡£
¼ÙÉèÎÒÃÇÒѾ½¨ÉèºÃÁËUserServiceºÍUserRepositoryÁ½¸öÀ࣬ÎÒÃÇÐèÒªÔÚÈÝÆ÷Öн«ËüÃÇ×¢²áÈçÏ£º
use appserviceUserService; use appepositoryUserRepository; return [ 'services' => [ UserService::class => function($container) { return new UserService( $container->get(UserRepository::class) ); }, ], 'repositories' => [ UserRepository::class => new UserRepository(), ], ];
µÇ¼ºó¸´ÖÆ
ÔÚÒÔÉÏ´úÂëÖУ¬ÎÒÃÇÊ×ÏȽ«UserServiceÀàºÍÆäÒÀÀµµÄUserRepositoryÀà×¢²áµ½Ð§ÀÍ(‘services’)ºÍ¿ÍÕ»(‘repositories’)µÄÀàÐÍÖС£ÆäÖÐЧÀÍÊÇ¿ÉÒÔ×¢ÈëµÄ£¬¶ø¿ÍÕ»ÊDz»ÐèҪעÈëµÄ£¬ÒÔÊÇЧÀÍÐèҪʹÓÃÒ»¸ö»Øµ÷º¯Êý½¨É蹤¾ß²¢×¢ÈëÒÀÀµ£¬¶ø¿ÍÕ»ÔòÖ±½ÓʵÀý»¯²¢×¢²á¡£
°ì·¨4£ºÊ¹ÓÃIocÈÝÆ÷
×îºó£¬ÎÒÃÇÐèҪʹÓÃIocÈÝÆ÷À´ÊµÀý»¯×¢²áµ½ÈÝÆ÷ÖеÄЧÀÍ¡£
ÔÚ×ðÁú¿Ê±Ê¾ÀýÖУ¬ÎÒÃÇ¿ÉÒÔÔÚ¿ØÖÆÆ÷ÖÐʹÓÃIocÈÝÆ÷×¢ÈëUserService²¢Å²ÓÃÒªÁì¡£ÔÚÏêϸ´úÂëÖУ¬ÎÒÃÇ¿ÉÒÔÕâÑùд£º
namespace appcontroller; use appserviceUserService; use thinkacadeContainer; class UserController { public function index() { $userService = Container::get(UserService::class); $userList = $userService->getUserList(); return json($userList); } }
µÇ¼ºó¸´ÖÆ
ÔÚÒÔÉÏ´úÂëÖУ¬ÎÒÃÇÊ×ÏÈʹÓÃÈÝÆ÷µÄgetÒªÁì»ñÈ¡UserServiceµÄʵÀý£¬È»ºóŲÓÃgetUserListÒªÁìÀ´»ñÈ¡Óû§ÁÐ±í£¬²¢½«ÁбíÒÔjsonÃûÌ÷µ»Ø¡£
Íê³ÉÒÔÉÏÉèÖúó£¬ÎÒÃǾÍÀֳɵØʹÓÃÁËThinkPHP6µÄIocÈÝÆ÷À´ÊµÏÖÒÀÀµ×¢Èë¡£
×ܽá
ÔÚ±¾ÎÄÖУ¬ÎÒÃÇÏêϸ½â˵ÁËÔõÑùʹÓÃThinkPHP6µÄIocÈÝÆ÷À´ÊµÏÖÒÀÀµ×¢È롣ͨ¹ýIocÈÝÆ÷£¬ÎÒÃÇ¿ÉÒÔ½«¹¤¾ßµÄÒÀÀµ×¢ÈëÓ빤¾ßµÄ½¨ÉèÊèÉ¢¿ªÀ´£¬Ê¹µÃ´úÂë¸üÒ×ÓÚÖÎÀíºÍά»¤¡£Í¬Ê±£¬IocÈÝÆ÷Ò²¿ÉÒÔ´ó´ó¼ò»¯×ðÁú¿Ê±´úÂëÂß¼£¬Ìá¸ß´úÂëµÄ¿ÉÖØÓÃÐԺͿɲâÊÔÐÔ¡£
ÒÔÉϾÍÊÇThinkPHP6ÖÐÔõÑùʹÓÃIocÈÝÆ÷ʵÏÖÒÀÀµ×¢È룿µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡