Laravel 入门笔记(2)

MVC 简介

MVC 是一种软件设计范式,能够有效的将业务逻辑、数据模型、界面显示的代码进行分离,使得页面的样式和交互的调整不会影响业务逻辑。(图片来自百度百科)

MVC.png

Laravel 的 MVC

MVC.png

Laravel 的 MVC 中添加了路由模块,简化了原有的配置复杂度,同时也能够将 URL 的配置进行统一的管理。

个人觉得 PHP 比较 Bug 的地方就是没有注解功能,不能像 Spring MVC 那样爽的飞起。或许是我对 PHP 的理解不够,还没认识到它🐂的地方。

Hello Laravel

routes

<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| This file is where you may define all of the routes that are handled
| by your application. Just tell Laravel the URIs it should respond
| to using a Closure or controller method. Build something great!
|
*/
 Route::get( '/articles', 'ArticlesController@index' );

controller

class ArticlesController extends Controller {
    public function index() {
        $articles = Article::latest()->published()->get();
        
        return view( 'articles.index', compact( 'articles' ) );
    }
}

model

class Article extends Model {
    protected $fillable = [ 'title', 'content', 'published_at' ];
    
    protected $dates = [ 'published_at' ];
    
    public function setPublishedAtAttribute( $date ) {
        $this->attributes['published_at'] = Carbon::createFromFormat( 'Y-m-d', $date );
    }
    
    public function scopePublished( $query ) {
        $query->where( 'published_at', '<=', Carbon::now() );
    }
}

views

<!DOCTYPE html>
<html>
<body>
    <h1>Articles</h1>
    <hr>
    @foreach($articles as $article)
        <h2><a href="{{ url('articles', $article->id) }}">{{ $article->title }}</a></h2>
        <article>
            <div>{{ $article->published_at->diffForHumans() }}</div>
            <div class="body">
                {{ $article->content }}
            </div>
        </article>
    @endforeach
</body>
</html>

show it

MVC.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容