Laravel4 basic tutorial: View, namespace, routing, laravel basic tutorial _ PHP Tutorial

Source: Internet
Author: User
Tags form post http authentication laravel tutorial
Laravel4 basic tutorial: Views, namespaces, and routes. Laravel4 basic tutorial: View, namespace, and routing; laravel basic tutorial 1. view Separation and nesting run the command phpartisangenerate: viewadmin in the learnlaravel folder. laravel 4 basic tutorial: View, namespace, and routing

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!


What is Laravel?

It can free you from the messy code like a noodle; it can help you build a perfect web APP, and each line of code can be concise and expressive. 1. Bundle is the extended package organization form or name of Laravel. Laravel's extension package repository is quite mature and can easily help you install the extension package (bundle) into your application. You can download an extension package (bundle) and copy it to the bundles directory, or use the command line tool "Artisan" for automatic installation. 2. Laravel already has an advanced PHP ActiveRecord implementation-Eloquent ORM. It can easily apply constraints to the two sides of the relationship, so that you have full control over the data and enjoy all the conveniences of ActiveRecord. Eloquent native supports all query-builder methods in Fluent. 3. Application Logic can be implemented in the controller or directly integrated into the route declaration. The syntax is similar to that of the Sinatra framework. Laravel's design philosophy is to provide developers with the maximum flexibility, both creating very small websites and building large-scale enterprise applications. 4. Reverse Routing gives you the ability to create a link (URI) using a routes name. You only need to use the route name. Laravel will automatically create the correct URI for you. In this way, you can change your routes at any time. Laravel will automatically update all related links. 5. Restful controller (Restful Controllers) is an optional method to differentiate the GET and POST request logic. For example, in a user login logic, you declare a get_login () action to process the service that obtains the login page, and also declare a post_login () action (action) to verify the data in the form POST, and after the verification, make the decision to redirect (redirect) to the login page or to the console. 6. the automatic loading Class simplifies the loading of the class. in the future, you do not need to maintain the automatic loading of configuration tables and non-essential components. When you want to load any library or model, use it immediately. Laravel will automatically help you load the required files. 7. View Composers is essentially a piece of code, which is automatically executed when the View is loaded. The best example is the recommendation of side random articles in the blog. the "view assembler" contains the logic for loading the recommendation of random articles. in this way, you only need to load the view of the content area) that's it. Laravel will automatically complete other tasks. 8. IoC container provides a convenient way to generate new objects, instantiate objects at any time, and access singleton objects. IoC means that you can access these objects from any location in the code without having to specifically load external libraries, it does not need to endure complicated and redundant code structures. 9. migration is like version control. However, it manages the database paradigm and is directly integrated into Laravel. You can use the "Artisan" command line tool to generate and execute the "migration" command. When your team members change the database paradigm, you can easily update the current project using a version control tool, and then execute the "migration command, your database is up to date! 11. the Automatic Pagination function prevents a large number of irrelevant page configuration code from being incorporated into your business logic. It is convenient that you do not need to remember the current page... the remaining full text>

What is Laravel?

It can free you from the messy code like a noodle; it can help you build a perfect web APP, and each line of code can be concise and expressive. 1. Bundle is the extended package organization form or name of Laravel. Laravel's extension package repository is quite mature and can easily help you install the extension package (bundle) into your application. You can download an extension package (bundle) and copy it to the bundles directory, or use the command line tool "Artisan" for automatic installation. 2. Laravel already has an advanced PHP ActiveRecord implementation-Eloquent ORM. It can easily apply constraints to the two sides of the relationship, so that you have full control over the data and enjoy all the conveniences of ActiveRecord. Eloquent native supports all query-builder methods in Fluent. 3. Application Logic can be implemented in the controller or directly integrated into the route declaration. The syntax is similar to that of the Sinatra framework. Laravel's design philosophy is to provide developers with the maximum flexibility, both creating very small websites and building large-scale enterprise applications. 4. Reverse Routing gives you the ability to create a link (URI) using a routes name. You only need to use the route name. Laravel will automatically create the correct URI for you. In this way, you can change your routes at any time. Laravel will automatically update all related links. 5. Restful controller (Restful Controllers) is an optional method to differentiate the GET and POST request logic. For example, in a user login logic, you declare a get_login () action to process the service that obtains the login page, and also declare a post_login () action (action) to verify the data in the form POST, and after the verification, make the decision to redirect (redirect) to the login page or to the console. 6. the automatic loading Class simplifies the loading of the class. in the future, you do not need to maintain the automatic loading of configuration tables and non-essential components. When you want to load any library or model, use it immediately. Laravel will automatically help you load the required files. 7. View Composers is essentially a piece of code, which is automatically executed when the View is loaded. The best example is the recommendation of side random articles in the blog. the "view assembler" contains the logic for loading the recommendation of random articles. in this way, you only need to load the view of the content area) that's it. Laravel will automatically complete other tasks. 8. IoC container provides a convenient way to generate new objects, instantiate objects at any time, and access singleton objects. IoC means that you can access these objects from any location in the code without having to specifically load external libraries, it does not need to endure complicated and redundant code structures. 9. migration is like version control. However, it manages the database paradigm and is directly integrated into Laravel. You can use the "Artisan" command line tool to generate and execute the "migration" command. When your team members change the database paradigm, you can easily update the current project using a version control tool, and then execute the "migration command, your database is up to date! 11. the Automatic Pagination function prevents a large number of irrelevant page configuration code from being incorporated into your business logic. It is convenient that you do not need to remember the current page... the remaining full text>

Http://www.bkjia.com/PHPjc/903472.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/903472.htmlTechArticleLaravel 4 elementary tutorial view, namespace, routing, laravel Elementary tutorial 1. view Separation and nesting in the learnlaravel folder run command: php artisan generate: view admin ....

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.