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 Eloquent ORM in Bangla partial model search) Laravel Eloquent ORM in Bangla partial model search) Apr 08, 2025 pm 02:06 PM

LaravelEloquent Model Retrieval: Easily obtaining database data EloquentORM provides a concise and easy-to-understand way to operate the database. This article will introduce various Eloquent model search techniques in detail to help you obtain data from the database efficiently. 1. Get all records. Use the all() method to get all records in the database table: useApp\Models\Post;$posts=Post::all(); This will return a collection. You can access data using foreach loop or other collection methods: foreach($postsas$post){echo$post->

How to effectively check the validity of Redis connections in Laravel6 project? How to effectively check the validity of Redis connections in Laravel6 project? Apr 01, 2025 pm 02:00 PM

How to check the validity of Redis connections in Laravel6 projects is a common problem, especially when projects rely on Redis for business processing. The following is...

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

Laravel database migration encounters duplicate class definition: How to resolve duplicate generation of migration files and class name conflicts? Laravel database migration encounters duplicate class definition: How to resolve duplicate generation of migration files and class name conflicts? Apr 01, 2025 pm 12:21 PM

A problem of duplicate class definition during Laravel database migration occurs. When using the Laravel framework for database migration, developers may encounter "classes have been used...

Laravel's geospatial: Optimization of interactive maps and large amounts of data Laravel's geospatial: Optimization of interactive maps and large amounts of data Apr 08, 2025 pm 12:24 PM

Efficiently process 7 million records and create interactive maps with geospatial technology. This article explores how to efficiently process over 7 million records using Laravel and MySQL and convert them into interactive map visualizations. Initial challenge project requirements: Extract valuable insights using 7 million records in MySQL database. Many people first consider programming languages, but ignore the database itself: Can it meet the needs? Is data migration or structural adjustment required? Can MySQL withstand such a large data load? Preliminary analysis: Key filters and properties need to be identified. After analysis, it was found that only a few attributes were related to the solution. We verified the feasibility of the filter and set some restrictions to optimize the search. Map search based on city

Laravel and the Backend: Powering Web Application Logic Laravel and the Backend: Powering Web Application Logic Apr 11, 2025 am 11:29 AM

How does Laravel play a role in backend logic? It simplifies and enhances backend development through routing systems, EloquentORM, authentication and authorization, event and listeners, and performance optimization. 1. The routing system allows the definition of URL structure and request processing logic. 2.EloquentORM simplifies database interaction. 3. The authentication and authorization system is convenient for user management. 4. The event and listener implement loosely coupled code structure. 5. Performance optimization improves application efficiency through caching and queueing.

Solve caching issues in Craft CMS: Using wiejeben/craft-laravel-mix plug-in Solve caching issues in Craft CMS: Using wiejeben/craft-laravel-mix plug-in Apr 18, 2025 am 09:24 AM

When developing websites using CraftCMS, you often encounter resource file caching problems, especially when you frequently update CSS and JavaScript files, old versions of files may still be cached by the browser, causing users to not see the latest changes in time. This problem not only affects the user experience, but also increases the difficulty of development and debugging. Recently, I encountered similar troubles in my project, and after some exploration, I found the plugin wiejeben/craft-laravel-mix, which perfectly solved my caching problem.

See all articles