search
HomeBackend DevelopmentPHP TutorialLaravel入门:MVC框架

本文基于Laravel 4.2编写。1. 路由Hello World在app/routes.php里面添加下面代码,然后在浏览器里访问http://<laravel host prefix>/helloworld可以见到结果。  ```Route::get('/helloworld', function() {  return '<html><body>hello world</body></html>';});```2.  视图(View)理论上可以把所有代码都写在app/routes.php里面,但是这会令代码难以维护。于是,我们可以把具体的页面内容搬到视图里,让路由文件简短一些。app/routes.php  ```Route::get('/helloworld', function() {  return View::make('helloworld');});app/views/helloworld.php  <html>  <body>    hello world  </body></html>```3. 控制器(Controller) 我们写的是动态网页,页面里有变量,变量通过Controller传入View。app/routes.php(这次我们的路由要先指向Controller,然后再由Controller返回View内容)  Route::get('/helloworld', 'HelloworldController@say');app/controllers/HelloworldController.php  ```<?phpclass HelloworldController extends BaseController {  public function say() {    $action = 'hello';    $name = 'kitty';    return View::make('hello.world', compact('action', 'name')); // hello.world表示hello目录里的world.php文件; 我们传入两个变量$action和$name  }}```app/views/hello/world.php(这次我们放在一个子目录里,避免views目录文件太多)  ```<html>  <body>    {{$action}} {{$name}}  </body></html>```页面将显示“hello kitty”4. 模型(Model)随着业务逻辑的复杂,Controller文件会变长不好维护,那么我们可以把和数据库查询相关的逻辑分到模型层里,甚至可以安排一个擅长数据库表设计和写SQL的人专门负责这一层。app/routes.php  ```Route::get('/helloworld', 'HelloworldController@say');app/controllers/HelloworldController.php  <?phpclass HelloworldController extends BaseController {  public function say() {    $name = 'kitty';    $contacts = Contact::getContacts();    return View::make('hello.world', compact('name', 'contacts'));  }}```app/models/Contact.php``` <?php// 假设有个表contacts(uid, name, phone)class Contact extends Eloquent {  public $timestamps = false;  protected $primaryKey  = 'uid';  static public function createContact($uid, $name, $phone) { // 这个方法只是演示Model可能有些什么内容,并没有实际调用。    $item = new Contact;    $item->uid = $uid;    $item->name = $name;    $item->phone = $phone;    $item->save();    return $item;  }  // 假设有两行内容:(1, ‘kitty’, ‘800888’), (2, 'dingdong', '900999')  static public function getContacts {    return DB::table('contacts')->get();  }}```app/views/hello/world.blade.php(由于需要使用循环等超越HTML语法的功能,我们需要使用blade模板语言,文件名里需要添加blade部分)  ```<html>  <body>@foreach ($contacts as $contact)    {{ $contact->name }}’s number is {{ $contact->phone }},@endforeach  </body></html>```页面将显示“kitty's number is 800888, dingdong's number is 900999,”模板语言更多语法可参考:https://laravel.com/docs/4.2/templates至此,MVC(Model-View-Controller)的框架进化完成。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

PHP Email Security: Best Practices for Sending EmailsPHP Email Security: Best Practices for Sending EmailsMay 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version