岁月不饶人,我亦未曾饶过岁月。
避免在模板中使用过多的复杂的判断,@inject 的用法
新建文件 app\Presenters\UserPresenter.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <?php namespace App\Presenters;
class UserPresenter { public function setName($name) { if ($name == 'Laurine Deckow') $fullName = 'Mr. ' . $name; else $fullName = 'Mrs. ' . $name;
return $fullName; } }
|
控制器 app\Http\Controllers\UserController.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <?php
namespace App\Http\Controllers;
use App\User;
class UserController extends Controller {
public function getUser() { $users = User::all(); return view('home/user',['users'=>$users]); } }
|
视图 resources\views\home\user.blade.php
1 2 3 4 5 6 7 8
| <ul class="list-group"> @inject('UserPresenter','App\Presenters\UserPresenter') @foreach($users as $user) <li class="list-group-item"> {{ $UserPresenter->setName($user->name) }} </li> @endforeach </ul>
|