Table of Contents
Hello!
Home php教程 php手册 跟我学Laravel之视图 & Response

跟我学Laravel之视图 & Response

Jun 06, 2016 pm 08:18 PM
laravel response view

这篇文章主要介绍了Laravel框架的视图 Response,非常简单实用,需要的朋友可以参考下

基本Response

从路由中返回字符串

复制代码 代码如下:


Route::get('/', function()
{
    return 'Hello World';
});

创建自定义Response

Response类继承自Symfony\Component\HttpFoundation\Response类,提供了多种方法用于构建HTTP Response。

复制代码 代码如下:


$response = Response::make($contents, $statusCode);

$response->header('Content-Type', $value);

return $response;

如果需要访问 Response 类的方法,但又要返回一个视图作为响应的内容,通过使用 Response::view 方法可以很容易实现:

复制代码 代码如下:


return Response::view('hello')->header('Content-Type', $type);

在Response中添加Cookie

复制代码 代码如下:


$cookie = Cookie::make('name', 'value');

return Response::make($content)->withCookie($cookie);

重定向

返回一个重定向

return Redirect::to('user/login');
返回一个带有数据的重定向

return Redirect::to('user/login')->with('message', 'Login Failed');
注意: with 方法将数据写到了Session中,通过Session::get 方法即可获取该数据。
返回一个重定向至命名路由

return Redirect::route('login');
返回一个重定向至带有参数的命名路由

return Redirect::route('profile', array(1));
返回一个重定向至带有命名参数的命名路由

return Redirect::route('profile', array('user' => 1));
返回一个重定向至控制器Action

return Redirect::action('HomeController@index');
返回一个重定向至控制器Action并带有参数

return Redirect::action('UserController@profile', array(1));
返回一个重定向至控制器Action并带有命名参数

return Redirect::action('UserController@profile', array('user' => 1));

视图

视图通常包含应用中的HTML代码,为分离表现层与控制器和业务逻辑提供了便利。视图存放于app/views目录。

一个简单视图案例:

复制代码 代码如下:



   


       

Hello,


   

通过如下方法来返回该视图到浏览器:

复制代码 代码如下:


Route::get('/', function()
{
    return View::make('greeting', array('name' => 'Taylor'));
});

传递给View::make方法的第二个参数是一个数组,它将被传递给视图。

传递数据给视图

复制代码 代码如下:


// Using conventional approach
$view = View::make('greeting')->with('name', 'Steve');

// Using Magic Methods
$view = View::make('greeting')->withName('steve');

在上面的案例中,$name变量在视图内是可以访问的,其值为Steve。

你还可以在所有视图同共享同一数据:

View::share('name', 'Steve');

向视图传递子视图

或许你可能想将一个视图放入到另一个视图中。例如,将存放在app/views/child/view.php文件中的子视图传递给另一视图,如下:

复制代码 代码如下:


$view = View::make('greeting')->nest('child', 'child.view');

$view = View::make('greeting')->nest('child', 'child.view', $data);

在父视图就可以输出该子视图了:

复制代码 代码如下:



   


       

Hello!


       
   

视图合成器

视图合成器可以是回调函数或者类方法,它们在创建视图时被调用。如果你想在应用程序中,每次创建视图时都为其绑定一些数据,使用视图合成器可以将代码组织到一个地方。因此,视图合成器就好像是 “视图模型”或者是“主持人”。

定义一个视图合成器

复制代码 代码如下:


View::composer('profile', function($view)
{
    $view->with('count', User::count());
});

现在,每次创建profile视图时,count都会被绑定到视图中。

你也可以为多个视图同时绑定一个视图合成器:

复制代码 代码如下:


View::composer(array('profile','dashboard'), function($view)
{
    $view->with('count', User::count());
});

如果你更喜欢使用基于类的视图合成器,IoC container可以提供更多便利,如下所示:

View::composer('profile', 'ProfileComposer');

视图合成器类定义如下:

复制代码 代码如下:


class ProfileComposer {

    public function compose($view)
    {
        $view->with('count', User::count());
    }

}

注意,,没有规定视图合成器类存放在哪里。因此,你可以任意存放,只要能在composer.json文件中指定位置并自动加载即可。

视图创建器

视图 创建器 与视图合成器的工作方式几乎完全相同;区别在于当一个视图被实例化后就会立即触发视图创建器。视图创建器通过 creator 方法方便地定义:

复制代码 代码如下:


View::creator('profile', function($view)
{
    $view->with('count', User::count());
});

特殊Response

创建一个JSON Response

return Response::json(array('name' => 'Steve', 'state' => 'CA'));
创建一个JSONP Response

return Response::json(array('name' => 'Steve', 'state' => 'CA'))->setCallback(Input::get('callback'));
创建一个文件下载Response

return Response::download($pathToFile);

return Response::download($pathToFile, $status, $headers);
注意: Symfony HttpFoundation 用于处理文件下载,要求下载的文件的文件名只包含 ASCII 字符。

Response 宏

如果希望自定义一个 response ,以便在你应用程序中的许多路由和控制器中进行重用,可以使用 Response::macro 方法:

复制代码 代码如下:


Response::macro('caps', function($value)
{
    return Response::make(strtoupper($value));
});

macro 方法接受两个参数,一个指定和名称和一个闭包。当通过 Response 类调用该名称的宏时,闭包就会被执行:

return Response::caps('foo');
你可以在 app/start 目录里的文件中定义宏。或者,你也可以通过一个单独的文件组织你的宏,并将该文件包含至某个 start 文件中。

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to get the return code when email sending fails in Laravel? How to get the return code when email sending fails in Laravel? Apr 01, 2025 pm 02:45 PM

Method for obtaining the return code when Laravel email sending fails. When using Laravel to develop applications, you often encounter situations where you need to send verification codes. And in reality...

Laravel schedule task is not executed: What should I do if the task is not running after schedule: run command? Laravel schedule task is not executed: What should I do if the task is not running after schedule: run command? Mar 31, 2025 pm 11:24 PM

Laravel schedule task run unresponsive troubleshooting When using Laravel's schedule task scheduling, many developers will encounter this problem: schedule:run...

In Laravel, how to deal with the situation where verification codes are failed to be sent by email? In Laravel, how to deal with the situation where verification codes are failed to be sent by email? Mar 31, 2025 pm 11:48 PM

The method of handling Laravel's email failure to send verification code is to use Laravel...

How to implement the custom table function of clicking to add data in dcat admin? How to implement the custom table function of clicking to add data in dcat admin? Apr 01, 2025 am 07:09 AM

How to implement the table function of custom click to add data in dcatadmin (laravel-admin) When using dcat...

Laravel - Dump Server Laravel - Dump Server Aug 27, 2024 am 10:51 AM

Laravel - Dump Server - Laravel dump server comes with the version of Laravel 5.7. The previous versions do not include any dump server. Dump server will be a development dependency in laravel/laravel composer file.

Laravel Redis connection sharing: Why does the select method affect other connections? Laravel Redis connection sharing: Why does the select method affect other connections? Apr 01, 2025 am 07:45 AM

The impact of sharing of Redis connections in Laravel framework and select methods When using Laravel framework and Redis, developers may encounter a problem: through configuration...

Laravel multi-tenant extension stancl/tenancy: How to customize the host address of a tenant database connection? Laravel multi-tenant extension stancl/tenancy: How to customize the host address of a tenant database connection? Apr 01, 2025 am 09:09 AM

Custom tenant database connection in Laravel multi-tenant extension package stancl/tenancy When building multi-tenant applications using Laravel multi-tenant extension package stancl/tenancy,...

Laravel - Action URL Laravel - Action URL Aug 27, 2024 am 10:51 AM

Laravel - Action URL - Laravel 5.7 introduces a new feature called “callable action URL”. This feature is similar to the one in Laravel 5.6 which accepts string in action method. The main purpose of the new syntax introduced Laravel 5.7 is to directl

See all articles