Laravel 4 Introductory Tutorial view, namespaces, routing, Laravel Beginner tutorial _php Tutorial

Source: Internet
Author: User
Tags autoload getting started with php http authentication ruby on rails laravel tutorial

Laravel 4 Primary Tutorial view, namespaces, routing, Laravel Beginner's tutorial


1. View Separation and nesting

Run the command under the Learnlaravel folder:

PHP Artisan Generate:view Admin._layouts.default

This time the generator plugin helped us create the app/views/admin/_layouts/default.blade.php file, modifying the content to:





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






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




@yield (' main ')


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

Views folder is a view folder, the View folder can be nested, like I created a admin/_layout nested folder, Created a file called default.blade.php in it, then we will be in the laravel anywhere in the use of this view, he called Admin._layouts.default.

As we can see, the seventh line of the above code is "@include (' admin._partials.assets '), according to the knowledge we have just learned, which means that another file is loaded. Blade is the template engine for Laravel, where the @include means to bring all the code of that file directly into it and put it in here as part of the current view.

Take a look at line 25th "@yield (' main '), what does that mean?" This is a bit complicated, we'll talk about it later.

2. Permission Validation

Laravel supports standard HTTP authentication, but here we need to build blog system, so we will write a perfect admin login system, login from the page.

Use the command line to create the app/views/admin/auth/login.blade.php file with the following code:

@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::p assword (' Password ')}}



{{form::submit (' Login ', Array (' class ' = ' = ' btn btn-inverse btn-login ')}}}

{{form::close ()}}

@stop

You should be aware of the first two lines:

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

What does this mean? In fact, in the future we will understand that when invoking the view in the controller, the call is just this login.blade.php file, the first line indicates that this view is Admin._ Layouts.default, when the blade engine will load this view in, how to assemble it? The next @section (' main ') should appear, and the code it wraps will be placed directly in the @yield (' main ') in Admin._layouts.default. Section and yield can be paired with each other, as long as there are call relationships between the two views, they can be used this way, very flexible.

You may have a question written here, why are there so many empty lines in the sample code? This is a personal experience. Blade engine all the tags will be in the view compile with regular processing, the engine itself has a problem, is not a bug, that is, the line break will be processed, resulting in the front and back line and this line are tightly squeezed together, in the Frontend browser "view Source" when the comparison is not clear, before and after the line can solve the problem. Of course this may be an automatic "compression" feature that is no longer discussed in depth.

Add controller file app/controllers/admin/authcontroller.php, this time someone said, this I know, haha, run

"PHP artisan generate:controller Admin. Authcontroller "

The idea is right, but do you want to run it and try it? A "admin" will be created directly under the App/controllers directory. authcontroller.php "file, someone said, then I use" Admin/authcontroller "head, you try? Or not. So we have to manually create the Admin folder under App/controllers, and then the command line input:

PHP Artisan Generate:controller Admin/authcontroller

That's all you can do. Next rewrite the contents of authcontroller.php:

<?php
namespace App\controllers\admin;
Use Auth, Basecontroller, Form, Input, Redirect, Sentry, View;
Class Authcontroller extends Basecontroller {
/**
* Show Login Page
* @return View
*/
Public Function GetLogin ()
{
Return View::make (' Admin.auth.login ');
}
/**
* POST Login 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 that we logged in, logged out, and C in MVC. Next I will explain the namespace, which is the basis of laravel, or is the basis of composer, is the whole laravel tutorial focus, difficult, I hope you pinching irritate D, any do not understand do not let go. You can go to the Phphub forum or the Golaravel forum to ask the appropriate post, or directly post questions.

We first look at the location of this file, which is located in the App/controllers/admin directory, what is the difference? In other frameworks such as CI, subfolders can be called directly with the folder name, although there can be at most one layer. And Laravel is not so simple, it involves the namespace of PHP.

1. Composer supports the PSR-0 and PSR-4 standards, and the standard specifies that PHP packages are distinguished by namespaces, and that all exposed classes should be under the \ author name \ Package name namespace, such as the \lui\mffc\mail class. In this way, even if the name of the package as long as the different authors can coexist on the https://packagist.org/for everyone to use.

2. Namespaces can be likened to a directory in a Linux system, in any directory can be directly using the file name to open all files and executable programs in the current directory, if you need to open files in other directories, you need to use absolute path or relative path.

3. You may have seen in many other tutorials that controller head does not have a NAMESAPCE declaration, and there is no such a heap of use XXX, like this file https://github.com/cecoo/laravel4demo/blob/ master/app/controllers/blogcontroller.php. This file in line 8th directly uses the Blog this class, this is why?

Because they are already declared in Learnlaravel this composer app's config file to be loaded automatically, and they don't declare their namespace at the top, they are automatically added to the top-level namespace. This configuration file is Composer.json, and the object configuration item is the CLASSMAP item under AutoLoad. This statement will allow Composer to automatically scan all classes and all subfolders of the file when generating the file automatically, as long as it does not declare a specific namespace, it will automatically be loaded as a top-level space. "The previous statement was incorrect and hereby corrected!" 】

For more information about namespaces, refer to "Getting Started with PHP namespaces".

OK, so far our MVC ternary has been set, so what's next? Configure the route. The route here is not the home with no line by the:-D, but the user requested the URL to the controller of a method of conversion, function is the smallest unit of code snippet in PHP, so the user requested a path, such as Http://ooxx.com/fuck/me, After the URL is routed, the route is parsed, which function should be called, and the result will be returned to the user.

Laravel routes return results in closures, adding the following in 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::p ost (' 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 means hold two GET request and a POST request, below is a routing group, specify a prefix admin, add a filter, auth.admin, internal has a can adapt to get and POST request '/' path, its full path is http:/ /ooxx.com/admin/. The remaining two resource controllers are essentially shorthand, and the corresponding table of the method names in the URL and controller classes is shown in the resource controller.

The filter mentioned above is Auth.admin, a request filter provided by Laravel, which is located next to the routing file, app/filters.php, at the end of the file:

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

So our authorization verification is done. The above code means that before entering any of the routes in this routing group, the filter is Auth.admin, which invokes Sentry::check (), and if False, will enter the if code block to jump the user's request to Name Route ' Admin.login ', name the routing document. From the name of this named route everyone can see, is to say with the visitors: "Stupid, what to do, log in to ~

Here the "named route" function is to imitate the Ruby on Rails "Link_to" to the object's routing binding function, but the PHP upload is the deployment of non-daemon features, so that we can not maintain a full code of the routing table, can not be implemented as Rails Resource routing-resource object-The function of the three bindings of routing call, can only make a semi-finished named route, artificially solves the need of changing the name while adjusting the/people to/human, and requiring the code to adapt itself.

At this point, we can try to access our project. Recommended configuration Apache points 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, and is not recommended to be accessed from a subfolder. If you don't, you can run

PHP Artisan Serve

Start the built-in HTTP server for PHP5.4. The address will be http://localhost:8000, note that 127.0.0.1 is not accessible here.

Below, we access the/admin in the browser, note that the URL will automatically jump to/admin/login, which means our filter is working, but you may get the following page


This means that the code is wrong. Next we modify app/config/app.php the first item is:

' Debug ' = True,

Refresh the page and the error message comes out! There is no feeling that the Laravel4.2 error is good looking ah, really good, but I do not think 4.1 before the good-looking:-D. I got the following error:


Say "App\controllers\admin\authcontroller" This class did not find, this is why? This file is obviously there.

This involves another problem, the autoload problem in Laravel. Laravel is based on a namespace, it will only automatically load classes of all top-level namespaces, that is, we have added this controller class is not in the top-level namespace, so you need to tell Laravel, I this class exists, how to tell it? Run

Composer Dump-autoload

Yes, refresh the page, he told me

View [admin._partials.assets] not found.

This is really, we haven't set up this file yet. Create an empty file, if it is built with generator, do not forget to delete the default contents of the inside OH. Refresh the page again, if there is a problem, I believe that you can solve the problem yourself.

OK, an ugly page appeared, why is it so ugly? (Why are pigeons so big?) Because we did not introduce any CSS and JS files, even the navigation bar of the HTML is not complete. It doesn't matter, come on, follow the code on my github and copy it to the appropriate file. Also, it is very important to copy the JS and CSS two folders under the public file in my project to your public folder completely.

Re-refresh, if you see the following page, stating that you have succeeded!

3. Try to log in

Add an administrator to seed and add an administrator group. Create a new app/database/seeds/sentryseeder.php with the content:

<?php
Class Sentryseeder extends Seeder {
Public Function Run ()
{
Db::table (' users ')->delete ();
Db::table (' groups ')->delete ();
Db::table (' users_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 ',
' Permissions ' = [' admin ' = + 1],
));
To join a user to a user group
$adminUser = Sentry::getuserprovider ()->findbylogin (' oo@xx.com ');
$adminGroup = Sentry::getgroupprovider ()->findbyname (' Admin ');
$adminUser->addgroup ($adminGroup);
}
}

Add a new line to app/database/seeds/databaseseeder.php:

$this->call (' Sentryseeder ');

Then run:

PHP Artisan Db:seed

After the success, the database will be found, the users, groups, Users_groups table has a new row. However, the articles and pages tables also add 10 rows to each other, yes, seed is such a stupid ^_^

Let's try to login! If you get:

Class App\controllers\admin\pagescontroller does not exist

It means you've done it!


What is Laravel?

It frees you from the messy code of noodles, and it helps you build a perfect web app, and every line of code can be concise and expressive. 1, Bundle is Laravel expansion package organization form or salutation. Laravel's expansion pack warehouse is quite mature and can easily be used to install expansion packs (bundles) into your application. You can choose to download an expansion pack (bundle) and then copy it to the bundles directory, or install it automatically via the command line tool "Artisan". 2, in Laravel already has a set of advanced PHP ActiveRecord implementation-eloquent ORM. It makes it easy to apply "constraints" to both sides of the relationship, so you have full control over the data and enjoy all the conveniences of ActiveRecord. Eloquent native supports all methods of the query constructor (Query-builder) in fluent. 3. Application logic (application logic) can be implemented either in the controller (controllers) or directly into the route declaration, and the syntax is similar to the Sinatra framework. Laravel's design philosophy is to give developers maximum flexibility to create very small websites and build large enterprise applications. 4. Reverse Routing (Reverse Routing) gives you the ability to create a link (URI) by routing (routes) name. Simply use the route name, Laravel will automatically help you create the correct URI. This way you can change your routing (routes) at any time, and Laravel will automatically update all relevant links for you. 5. RESTful controller (restful Controllers) is an optional way to differentiate between get and post request logic. For example, in a user login logic, you declare a get_login () action to handle the service that gets the landing page, and also declare a post_login () action to verify the data that the form is post, and after verification, Make a decision to re-turn (redirect) to the landing page or to the console. 6. The auto-load class (class auto-loading) simplifies the loading of classes, so that it is not necessary to maintain automatic loading of configuration tables and non-essential component loading work. When you want to load any library or model, use it immediately, and Laravel will automatically load the required files for you. 7. View composers is essentially a piece of code, whichThe segment code is automatically executed when the view is loaded. The best example is the blog side of the random article recommendation, "View Assembler" contains the logic to load the recommended random article, so that you only need to load the content area of the Views (view) on the line, the other things laravel will help you to do it automatically. 8. The Reverse control container (IoC container) provides a convenient way to generate new objects, instantiate objects at any time, and Access Singleton (singleton) objects. Reverse control (IoC) means that you hardly need to intentionally load external libraries (libraries) to access them anywhere in your code, and you don't have to tolerate cumbersome, redundant code structures. 9. Migration (migrations) is like a version control tool, but it manages the database paradigm and is integrated directly into the laravel. You can use the "Artisan" command-line tool to generate and execute "migration" instructions. When your team member changes the database paradigm, you can easily update the current project through the version Control tool and then execute the "migration instructions," OK, your database is up to date! 11. The automatic paging (Automatic pagination) feature avoids the mixing of a large number of unrelated paging configuration codes in your business logic. Convenient is no need to remember the current page ... Remaining full text >>

What is Laravel?

It frees you from the messy code of noodles, and it helps you build a perfect web app, and every line of code can be concise and expressive. 1, Bundle is Laravel expansion package organization form or salutation. Laravel's expansion pack warehouse is quite mature and can easily be used to install expansion packs (bundles) into your application. You can choose to download an expansion pack (bundle) and then copy it to the bundles directory, or install it automatically via the command line tool "Artisan". 2, in Laravel already has a set of advanced PHP ActiveRecord implementation-eloquent ORM. It makes it easy to apply "constraints" to both sides of the relationship, so you have full control over the data and enjoy all the conveniences of ActiveRecord. Eloquent native supports all methods of the query constructor (Query-builder) in fluent. 3. Application logic (application logic) can be implemented either in the controller (controllers) or directly into the route declaration, and the syntax is similar to the Sinatra framework. Laravel's design philosophy is to give developers maximum flexibility to create very small websites and build large enterprise applications. 4. Reverse Routing (Reverse Routing) gives you the ability to create a link (URI) by routing (routes) name. Simply use the route name, Laravel will automatically help you create the correct URI. This way you can change your routing (routes) at any time, and Laravel will automatically update all relevant links for you. 5. RESTful controller (restful Controllers) is an optional way to differentiate between get and post request logic. For example, in a user login logic, you declare a get_login () action to handle the service that gets the landing page, and also declare a post_login () action to verify the data that the form is post, and after verification, Make a decision to re-turn (redirect) to the landing page or to the console. 6. The auto-load class (class auto-loading) simplifies the loading of classes, so that it is not necessary to maintain automatic loading of configuration tables and non-essential component loading work. When you want to load any library or model, use it immediately, and Laravel will automatically load the required files for you. 7. View composers is essentially a piece of code, whichThe segment code is automatically executed when the view is loaded. The best example is the blog side of the random article recommendation, "View Assembler" contains the logic to load the recommended random article, so that you only need to load the content area of the Views (view) on the line, the other things laravel will help you to do it automatically. 8. The Reverse control container (IoC container) provides a convenient way to generate new objects, instantiate objects at any time, and Access Singleton (singleton) objects. Reverse control (IoC) means that you hardly need to intentionally load external libraries (libraries) to access them anywhere in your code, and you don't have to tolerate cumbersome, redundant code structures. 9. Migration (migrations) is like a version control tool, but it manages the database paradigm and is integrated directly into the laravel. You can use the "Artisan" command-line tool to generate and execute "migration" instructions. When your team member changes the database paradigm, you can easily update the current project through the version Control tool and then execute the "migration instructions," OK, your database is up to date! 11. The automatic paging (Automatic pagination) feature avoids the mixing of a large number of unrelated paging configuration codes in your business logic. Convenient is no need to remember the current page ... Remaining full text >>

http://www.bkjia.com/PHPjc/903472.html www.bkjia.com true http://www.bkjia.com/PHPjc/903472.html techarticle Laravel 4 Beginner Tutorial View, namespaces, routing, Laravel Beginner tutorial 1. View detach with nested in 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.