Laravel4 basic Tutorial: View, namespace, route _ php instance

Source: Internet
Author: User
Tags autoload http authentication laravel tutorial
This is the second article in Laravel4's elementary tutorial. After learning to enter the deep water area, I will focus on common view rules, namespaces (important and difficult), and routing (difficult ). 1. View separation and nesting

Run the following command in the learnlaravel Folder:

php artisan generate:view admin._layouts.default

At this time, the generator plug-in helped us create the app/views/admin/_ layouts/default. blade. php file and modify the content:





Learn Laravel 4
@include('admin._partials.assets')






Learn Laravel 4
@include('admin._partials.navigation')





@yield('main')



This is the view file V in MVC. The view needs to be carefully discussed.

The views folder is a view folder, which can be nested. Just like above, the admin/_ layout nested folder is created and a default folder is created. blade. php file, so when we need to use this view anywhere in Laravel, it will be called admin. _ layouts. default.

We can see that the seventh line of the code above is "@ include ('admin. _ partials. asset')". Based on the knowledge we just learned above, this indicates that another file is loaded. Blade is Laravel's template engine. @ include here indicates that all the code of the file is directly brought in and put into the current view.

Note that line 3 "@ yield ('main')" indicates what? This is a bit complicated. Let's talk about it later.

2. Permission Verification

Laravel supports standard HTTP authentication, but here we need to build a blog system, so we will write a complete administrator login system to log on from the page.

Use the command line to create the app/views/admin/auth/login. blade. php file. The Code is as follows:

@extends('admin._layouts.default')
@section('main')


{{ Form::open() }}
@if ($errors->has('login'))

{{ $errors->first('login', ':message') }}


@endif


{{ Form::label('email', 'Email') }}


{{ Form::text('email') }}




{{ Form::label('password', 'Password') }}


{{ Form::password('password') }}




{{ Form::submit('Login', array('class' => 'btn btn-inverse btn-login')) }}


{{ Form::close() }}


@stop

You should note the first two lines:

@extends('admin._layouts.default')@section('main')

What does this mean? In fact, we will learn later that when calling view in the controller, This login is called only. blade. PHP file. The first line indicates that the view is admin. _ layouts. in this case, the blade Engine will load the default sub-view. How can this view be assembled? At this time, the @ section ('main') below should be displayed. The wrapped code will be directly placed in @ yield ('main') in admin. _ layouts. default. Section and yield can be used in any way. As long as there is a call relationship between the two views, they can be used in this way, which is very flexible.

You may be wondering why there are so many blank lines in the sample code? This is my personal experience. All the labels of the blade engine will be processed using regular expressions during view compilation. The engine itself has a problem that is not a bug, that is, line breaks will be processed, as a result, both the front and back lines are tightly integrated with this line. It is unclear when "view source code" in the front-end browser. Adding blank lines before and after the browser can solve this problem. Of course, this may be an automatic "compression" feature and will not be discussed in depth.

Add the Controller file app/controllers/admin/AuthController. php. At this time someone said, I know, haha, run

"Php artisan generate: controller admin. AuthController"

This idea is correct, but can you try it? A "admin. AuthController. php" file will be created directly in the app/controllers directory. Someone said, I will use the "admin/AuthController" line. Would you like to give it a try? No. Therefore, you must manually create the admin folder under app/controllers. Then, run the following command:

php artisan generate:controller admin/AuthController

In this way, you can. Next, rewrite AuthController. php:

<? Php
Namespace App \ Controllers \ Admin;
Use Auth, BaseController, Form, Input, Redirect, Sentry, View;
Class AuthController extends BaseController {
/**
* The logon page is displayed.
* @ Return View
*/
Public function getLogin ()
{
Return View: make ('admin. auth. login ');
}
/**
* POST logon Verification
* @ Return Redirect
*/
Public function postLogin ()
{
$ Credentials = array (
'Email '=> Input: get ('email '),
'Password' => Input: get ('Password ')
);
Try
{
$ User = Sentry: authenticate ($ credentials, false );
If ($ user)
{
Return Redirect: route ('admin. pages. Index ');
}
}
Catch (\ Exception $ e)
{
Return Redirect: route ('admin. login')-> withErrors (array ('login' => $ e-> getMessage ()));
}
}
/**
* Logout
* @ Return Redirect
*/
Public function getLogout ()
{
Sentry: logout ();
Return Redirect: route ('admin. login ');
}
}

This is the controller we log on to and log off, C in MVC. Next, I will explain the namespace. This is the basis of Laravel, or the basis of composer. It is the key and difficult part of the entire Laravel tutorial. I hope you will never miss it unless you understand it. You can go to the phphub Forum or the golaravel forum to ask questions, or directly post questions.

First, observe the location of the file. It is located in the app/controllers/admin directory. What is the difference? In other frameworks such as CI, you can directly add a folder name to the sub-folder, although there can be only one layer at most. Laravel is not as simple as it involves the PHP namespace.

1. composer supports PSR-0 and PSR-4 standards, which stipulate that PHP packages are distinguished by namespaces and provide services externally. All exposed classes should be under the \ author name \ package namespace, for example, \ lui \ MFFC \ Mail class. In this way, even packages with the same name can be stored on https://packagist.org/for use by different authors.

2. a namespace can be analogous to a directory in a Linux system. In any directory, you can directly use a file name to open all files and executable programs in the current directory. If you need to open files in other directories, the absolute or relative path is required.

3. You may have seen in many other Tutorials that the controller header does not have the namesapce statement, not the heap of use xxx, like this file https://github.com/cecoo/laravel4demo/blob/master/app/controllers/BlogController. php. This file directly uses the Blog class in Row 3. Why?

Because they have already declared automatic loading in the configuration file of the composer application learnlaravel, and they have not declared their namespace at the top, this will be automatically added as a top-level namespace. This configuration file is composer. json, and the object configuration item is the classmap item under autoload. This statement will enable Composer to automatically scan all the classes in the file and the classes in all subfolders when generating an automatically loaded file, as long as no specific namespace is declared, will be automatically loaded as top-level space. [The previous statement is incorrect. Please correct it !]

For more information about namespaces, refer to [PHP namespaces getting started ].

OK. So far, our MVC three elements have been integrated. What should we do next? Configure the route. Here, the route is not a wireless route used at home:-D, but the conversion from the URL requested by the user to a method of the controller. function is the smallest unit of the code segment in PHP, so the user requests a path, such as http://ooxx.com/fuck/me, this URL to the route, the route will go to the Resolution, which function should be called, and finally return the result to the user.

Laravel routes return results using closures and add the following content to app/routes. php:

Route::get('admin/logout', array('as' => 'admin.logout', 'uses' => 'App\Controllers\Admin\AuthController@getLogout'));
Route::get('admin/login', array('as' => 'admin.login', 'uses' => 'App\Controllers\Admin\AuthController@getLogin'));
Route::post('admin/login', array('as' => 'admin.login.post', 'uses' => 'App\Controllers\Admin\AuthController@postLogin'));
Route::group(array('prefix' => 'admin', 'before' => 'auth.admin'), function()
{
Route::any('/', 'App\Controllers\Admin\PagesController@index');
Route::resource('articles', 'App\Controllers\Admin\ArticlesController');
Route::resource('pages', 'App\Controllers\Admin\PagesController');
});

The first three items mean holding two get requests and one post request. Below is a routing group, specifying a prefix admin and adding a filter, auth. admin, which has a '/' path that can adapt to both get and post requests. The complete path is http://ooxx.com/admin /. The remaining two resource controllers are simply abbreviated. For details about the method names in the URL and controller classes, see resource controllers.

The above filter auth. admin is a request filter provided by Laravel. This file is next to the route file, app/filters. php, and is added at the end of the file:

Route::filter('auth.admin', function()
{
if ( ! Sentry::check()) {
return Redirect::route('admin.login');
}
});

In this way, the permission verification is complete. The above Code indicates that auth is performed first before any route entry in the routing group. admin filter, which will call Sentry: check (). if it is false, it will enter the if code block and redirect the user's request to the named route 'admin. login', named routing document. We can also see from the name of this named route, that is, to say to the visitor: What are you doing? log on ~

Here, the "named routing" function is used to simulate the routing binding function from "link_to" of Ruby On Rails to an object. However, you can deploy the feature without a daemon by uploading PHP, this makes it impossible for us to maintain a route table with full code and to implement the function of binding resource routing, resource object, and route call as Rails. We can only create a half-product named route, when adjusting/people to/human, the name is required to change but the function is not changed, and the code is required to be adaptive.

At this time, we can try to access our project. We recommend that you configure Apache to direct a port to the public directory of the learnlaravel project, that is, the project is accessed through an address such as http: // 127.0.0.1: 8080. Therefore, it is not recommended to access the project from subfolders. If you do not, you can run

php artisan serve

Start the built-in HTTP server of PHP5.4. The address will be http: // localhost: 8000. Note that 127.0.0.1 cannot be accessed.

Next, we access/admin in the browser. Note that the URL will automatically jump to/admin/login, which indicates that our filter works, but you may get the following page


This indicates that the Code has an error. Next, modify app/config/app. php. The first item is:

'debug' => true,

Refresh the page and the error message is displayed! Do you think Laravel4.2's error prompt looks good? It's really good, but I don't think it looks good before 4.1:-D. I got the following error:


The class "App \ Controllers \ Admin \ AuthController" is not found. Why? This file is clearly available.

This involves another issue, the autoload problem in Laravel. Laravel is based on the namespace. It only automatically loads all the classes in the top-level namespace. That is to say, the Controller class we added is not under the top-level namespace, so we need to tell Laravel, my class exists. How can I tell it? Run

composer dump-autoload

Yes. Refresh the page and tell me.

View [admin. _ partials. assets] not found.

This is indeed because we have not yet created this file. Create an empty file. If you use generator, do not forget to delete the default content. Refresh the page again. If there is still a problem, I believe you can solve it by yourself.

OK. Why is an ugly page displayed? (Why are pigeons so big ?) Because we didn't introduce any css and js files, and even the html in the navigation bar was incomplete. It doesn't matter. Follow the code on github and copy it to the corresponding file. In addition, it is very important to copy the js and css folders under the public file in my project to your public folder.

Refresh again. If you see the following page, it means you have succeeded!

3. Try to log on

Use seed to add an administrator and add an Administrator group by the way. Create app/database/seeds/SentrySeeder. php with the following content:

<? Php
Class SentrySeeder extends Seeder {
Public function run ()
{
DB: table ('users')-> delete ();
DB: table ('groups ')-> delete ();
DB: table ('ers _ groups ')-> delete ();
Sentry: getUserProvider ()-> create (array (
'Email '=> 'oo @ xx.com ',
'Password' => "ooxx ",
'First _ name' => 'oo ',
'Last _ name' => 'XX ',
'Activated' => 1,
));
Sentry: getGroupProvider ()-> create (array (
'Name' => 'admin ',
'Permission' => ['admin' => 1],
));
// Add a user to a user group
$ AdminUser = Sentry: getUserProvider ()-> findByLogin ('oo @ xx.com ');
$ AdminGroup = Sentry: getGroupProvider ()-> findByName ('admin ');
$ AdminUser-> addGroup ($ adminGroup );
}
}

Add a line to app/database/seeds/DatabaseSeeder. php:

$this->call('SentrySeeder');

Then run:

php artisan db:seed

After the operation is successful, a new row is added to the users, groups, and users_groups tables. However, the articles and pages tables also add 10 rows, right. seed is so stupid. ^_^

Let's try to log on! If you get:

Class App \ Controllers \ Admin \ PagesController does not exist

This indicates that you have succeeded!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.