laravel ·ÓÉ¿ØÖÆ·´×ª
laravel ÊÇÒ»¿îÊ¢ÐÐµÄ php ¿ª·¢¿ò¼Ü£¬¿ÉÒÔ×ÊÖú¿ª·¢Õß¿ìËÙ¸ßЧµØ¹¹½¨ web Ó¦ÓóÌÐò¡£×÷Ϊһ¸öÏÖ´ú»¯µÄ¿ò¼Ü£¬laravel ¼¯³ÉÁËÐí¶àÏȽøµÄ¹¦Ð§£¬ÆäÖÐÖ®Ò»¾ÍÊÇ·ÓÉ¿ØÖÆ·´×ª£¨inversion of control£©¡£
ÔÚ±¾ÎÄÖУ¬ÎÒÃǽ«Éî¶È̽ÌÖ Laravel ·ÓÉ¿ØÖÆ·´×ªµÄʵÏÖÔÀí¡¢ÓÅÊÆÒÔ¼°ÔõÑù׼ȷµØʹÓÃËüÀ´ÓÅ»¯ÄãµÄ Web Ó¦ÓóÌÐò¡£
·ÓÉ¿ØÖÆ·´×ªÊÇʲô£¿
·ÓÉ¿ØÖÆ·´×ª£¬ÓÖ³ÆΪÒÀÀµ×¢È루Dependency Injection£©£¬ÊÇÒ»ÖÖÅÌËã»ú±à³ÌÔÔò£¬Ëü½¨Ò齫¹¤¾ßÖ®¼äµÄÒÀÀµ·´×ª¹ýÀ´£¬ÒÔ±ãÌá¸ß´úÂëµÄ¸´ÓÃÐÔ¡¢¿Éά»¤ÐԺͲâÊÔÐÔ¡£ÔÚ Laravel ÖУ¬Â·ÓÉ¿ØÖÆ·´×ª¿ÉÒÔ×ÊÖúÎÒÃǸüºÃµØ×éÖ¯ÎÒÃǵÄÓ¦ÓóÌÐò£¬²¢Ê¹Æä¸üÈÝÒ×À©Õ¹ºÍά»¤¡£
ʹÓ÷ÓÉ¿ØÖÆ·´×ªµÄÓÅÊÆ
¸üÈÝÒ×À©Õ¹
Laravel ·ÓÉ¿ØÖÆ·´×ª¿ÉÒÔºÜÈÝÒ×µØʵÏÖ¹¤¾ßÖ®¼äµÄËÉÉ¢ñîºÏ¡£ÕâÒâζ×ÅÄãµÄ´úÂë¿ÉÒÔ¸üÈÝÒ×µØÀ©Õ¹ºÍÐ޸ģ¬¶ø²»»áÓ°Ïìµ½ÆäËû²¿·ÖµÄ´úÂë¡£
¸üÈÝÒ×ά»¤
ƾ֤·ÓÉ¿ØÖÆ·´×ªµÄÔÔò±àдµÄ´úÂëͨ³£ÊÇÄ£¿é»¯ºÍ¿ÉÖØÓõġ£ÕâʹµÃÔÚ¸üлòÐÞ¸´´úÂëʱ¸üÈÝÒ×ÕÒµ½ºÍÐÞ¸´¹ýʧ£¬¶ø²»»á±¬·¢ÆäËûÎÊÌâ¡£
¸üÈÝÒײâÊÔ
ʹÓ÷ÓÉ¿ØÖÆ·´×ª¿ÉÒÔʹ²âÊÔ¸üÈÝÒס£¹¤¾ßµÄ²âÊÔ¿ÉÒÔ¸üÈÝÒ׵ر»ÊèÉ¢³öÀ´²¢¸ü׼ȷµØ±»²âÊÔ¡£ÕâÒ²¿ÉÒÔ¸ÄÉÆ´úÂëµÄÕûÌåÖÊÁ¿¡£
Laravel ·ÓÉ¿ØÖÆ·´×ªµÄʵÏÖÔÀí
ÔÚ Laravel ÖУ¬Â·ÓÉ¿ØÖÆ·´×ªÍ¨³£»ùÓÚÒÀÀµ×¢ÈëÈÝÆ÷£¨Dependency Injection Container£©¾ÙÐÐʵÏÖ¡£ÕâÊÇÒ»¸öÓÃÓÚÖÎÀíºÍʵÏÖ¹¤¾ßÒÀÀµÐԵŤ¾ß¡£
ÏÂÃæÊÇÒ»¸ö¼òÆÓµÄʾÀý£¬ÑÝʾÁËÔõÑùÔÚ Laravel ÖÐʹÓÃÒÀÀµ×¢È룺
class UserController extends Controller { protected $db; public function __construct(Database $db) { $this->db = $db; } public function show($id) { $user = $this->db->find($id); return view('user.show', ['user' => $user]); } }
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÊöʾÀýÖУ¬ÎÒÃÇÐèҪʹÓà Database ÀàÀ´¼ìË÷Óû§µÄÐÅÏ¢¡£¿ÉÊÇÕâ¸öÀ಻ÊÇ Controller µÄÖ±½ÓÒÀÀµ£¬ÒÔÊÇÎÒÃÇÐèÒª½«Ëü´æ´¢µ½¸ÃÀàµÄ˽ÓÐÊôÐÔÖУ¬²¢Ôڽṹº¯ÊýÖн«Æä×¢Èë¡£ÕâÖÖ·½·¨ÔÊÐíÎÒÃÇ´Ó Controller ÀàÖÐÊèÉ¢³ö Database À࣬²¢ÔÚÐèҪʱÇáËɵØÌæ»»¹¤¾ß£¬²¢¼á³Ö´úÂëµÄËÉÉ¢ñîºÏ¡£
ÁíÒ»¸öʾÀýÊǽ«ÒÀÀµ·â×°ÔÚЧÀÍÈÝÆ÷ÖУº
class DatabaseServiceProvider extends ServiceProvider { public function register() { $this->app->singleton(Database::class, function ($app) { return new Database( $app->make(PDO::class), $app->config->get('database') ); }); } }
µÇ¼ºó¸´ÖÆ
ÔÚÕâ¸öʾÀýÖУ¬ÎÒÃÇʹÓà Laravel µÄÈÝÆ÷À´×¢²áµ¥Àý¹¤¾ß Database¡£ÕâÑùÎÒÃǾͿÉÒÔÔÚÕû¸öÓ¦ÓóÌÐòÖÐÇáËɵػñÈ¡ºÍ×¢Èë Database ÀàÁË¡£
ʹÓ÷ÓÉ¿ØÖÆ·´×ªµÄ×î¼Ñʵ¼ù
ʹÓÃÒÀÀµ×¢ÈëÈÝÆ÷
ÔÚ Laravel ÖУ¬ÈÝÆ÷ÊÇÒ»¸öÇ¿Ê¢µÄ¹¤¾ß£¬¿ÉÒÔ¼ò»¯ÒÀÀµ×¢Èë¡£µ±ÄãÐèҪʵÀý»¯Ò»¸ö¹¤¾ßʱ£¬ÈÝÆ÷»á×Ô¶¯ÆÊÎöºÍ×¢ÈëËùÓеÄÒÀÀµÏ²¢½«Æä×÷Ϊ½á¹¹º¯Êý²ÎÊýת´ï¡£ÕâÑù£¬Äã¾Í¿ÉÒÔ×èÖ¹ÔÚ´úÂëÖÐÊÖ¶¯×¢ÈëÒÀÀµÏ²¢ÔÊÐí Laravel ÈÝÆ÷À´ÈÏÕæÖÎÀíÒÀÀµÏîµÄÉúÃüÖÜÆÚ¡£
ÊèÉ¢ÓªÒµÂß¼
ÔÚʹÓ÷ÓÉ¿ØÖÆ·´×ªÊ±£¬Ó¦¾¡¿ÉÄܵؽ«ÓªÒµÂß¼ÊèÉ¢µ½×ÔÁ¦µÄÀàÖС£Õâ¿ÉÒÔʹÄãµÄ´úÂëÔ½·¢Ä£¿é»¯ºÍ¿É²âÊÔ£¬²¢ÃãÀøÖØÓôúÂë¡£
×ñÕÕ SOLID ÔÔò
SOLID ÔÔòÊǹ¤¾ßµ¼Ïò±à³ÌÖеÄÒ»×éÔÔò£¬ËüÃÇ×ÊÖúÄã±àд¿Éά»¤¡¢¿ÉÀ©Õ¹ºÍ¿É²âÊԵĴúÂë¡£ÔÚʹÓ÷ÓÉ¿ØÖÆ·´×ªÊ±£¬ÇëÈ·±£×ñÕÕÕâЩÔÔò£¬ÒÔÌá¸ß´úÂëµÄÕûÌåÖÊÁ¿¡£
С½á
·ÓÉ¿ØÖÆ·´×ªÊÇÒ»¸öÇ¿Ê¢µÄ¹¤¾ß£¬¿ÉÒÔ×ÊÖúÄã¸üºÃµØ×éÖ¯´úÂë¡¢Ìá¸ß¿Éά»¤ÐԺͿɲâÊÔÐÔ¡£ÔÚ Laravel ÖУ¬ÒÀÀµ×¢ÈëÈÝÆ÷ÌṩÁËÒ»ÖÖ¼òÆÓ¶øÓÅÑŵķ½·¨À´Ê¹ÓøÃÔÔò¡£ÇëÈ·±£×ñÕÕ×î¼Ñʵ¼ù£¬ÒÔ±ã×î´ó»¯Ê¹ÓøÃÌØÕ÷£¬Ìá¸ß´úÂëµÄÖÊÁ¿ºÍ¿Éά»¤ÐÔ¡£
ÒÔÉϾÍÊÇlaravel ·ÓÉ¿ØÖÆ·´×ªµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡