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