Home  >  Article  >  Backend Development  >  First introduction to laravel5, laravel5_PHP tutorial

First introduction to laravel5, laravel5_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:05:36782browse

First introduction to laravel5, laravel5

Directory structure changes

The first thing laravel5 emphasizes is the change in the project directory structure. The difference from 4.2 is quite big. Let’s talk about it one by one.

The new directory structure will look like this:

app
Commands
Console
Events
Handlers
Commands
Events
Http
        Controllers
              Middleware
Requests
Kernel.php
Routes.php
Providers
Services
bootstrap
config
database
migrations
seeds
public
package
resources
lang
Views
storage
cache
Logs
Meta
sessions
Views
Work
tests

Directory structure of 4.2:

app
commands
config
controllers
database
lang
models
Start
Storage
Tests
Views
bootstrap
public
In comparison, the changes are quite big. You can see that the config and database have been moved to the root directory, the lang and views directories have been moved to the resources directory, the controllers have been integrated into the http directory, the models directory has disappeared, and there are some new additions. The table of contents is omitted.

App Namespace

There is another change in laravel5, that is, the app directory has a root namespace App by default. All directories and classes under App should be under this namespace. In short, the psr4 standard is adopted.

HTTP

Laravel5 believes that the new directory structure is one of the best structures currently, which can make our development more convenient, such as http directory:

Http
Controllers
Middleware
Requests
Kernel.php
Routes.php
Middleware is very unfamiliar. In fact, it is an upgraded version of the original routing filter. Now there is no need to define filters in filters.php. Instead, create a class in the Middleware directory and configure it globally or optionally in Kernel.php. The middleware will be executed on every request, and the optional one is equivalent to the original filter, which can be used in routing or in controllers.

Requests is an extension of the core class Request. You can extend different Requests classes and add different functions.

It can be considered that all processing related to http requests are in the http directory. For example, the controller is used to accept a request and return it, so it is reasonable to place it in the Http directory.

Routing

The routing is not much different from the previous one, but it should be noted that when we specify the controller namespace, the namespace is not an absolute path, but relative to AppHttpControllers, for example:

Copy code The code is as follows:
Route::controllers([
'auth' => 'AuthAuthController',
'password' => 'AuthPasswordController',
]);

The corresponding class can be found in the App/Http/Controllers/Auth directory.

In addition, routing also supports caching to improve performance through command line tools

Copy code The code is as follows:
php artisan route:cache

can be easily generated, or you can use

Copy code The code is as follows:
php artisan route:clear

Clear cache.

Services

We see that there is also a Services directory under the App directory. I think this is a great concept. I have always been annoyed by the large sections of business logic code in the controller. I would like to use one A separate layer encapsulates these business logic, and services can be used to do this work. Of course, it is not necessary, but I strongly recommend it. Let’s take a look at the demo that comes with laravel5:

复制代码 代码如下:
# Http/Controllers/Auth/AuthController.php
use AppHttpControllersController;
use IlluminateContractsAuthGuard;
use IlluminateContractsAuthRegistrar;
use IlluminateFoundationAuthAuthenticatesAndRegistersUsers;
class AuthController extends Controller {
    /*
    |--------------------------------------------------------------------------
    | Registration & Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users, as well as the
    | authentication of existing users. By default, this controller uses
    | a simple trait to add these behaviors. Why don't you explore it?
    |
    */
    use AuthenticatesAndRegistersUsers;
    /**
     * Create a new authentication controller instance.
     *
     * @param  IlluminateContractsAuthGuard  $auth
     * @param  IlluminateContractsAuthRegistrar  $registrar
     * @return void
    */
    public function __construct(Guard $auth, Registrar $registrar)
    {
        $this->auth = $auth;
        $this->registrar = $registrar;
        $this->middleware('guest', ['except' => 'getLogout']);
    }
}

这是一个登陆授权的控制器,我们看 __construct构造函数,利用参数自动注入了一个 "接口实现(参考手册IoC)" 的绑定,我们看下Registrar:

复制代码 代码如下:
use AppUser;
use Validator;
use IlluminateContractsAuthRegistrar as RegistrarContract;
class Registrar implements RegistrarContract {
    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return IlluminateContractsValidationValidator
    */
    public function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|confirmed|min:6',
        ]);
    }
    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
    */
    public function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
    }
}

提交用户名密码时的处理:

Copy code The code is as follows:
public function postRegister(Request $request)
{
$validator = $this->registrar->validator($request->all());
If ($validator->fails())
{
           $this->throwValidationException(
               $request, $validator
);
}
$this->auth->login($this->registrar->create($request->all()));
Return redirect($this->redirectPath());
}

As you can see, the business logic of form validation is only one line:

Copy code The code is as follows:
$validator = $this->registrar->validator($request->all());

The code of the entire controller is clean and easy to read. We can encapsulate a lot of common business logic into services, which is better than encapsulating it directly in the controller class.

Model

The models directory is missing, because not all applications need to use a database, so it is understandable that laravel5 does not provide this directory by default, and since the App namespace is provided, we can create the Models directory ourselves under App/, where All model classes declare namespace AppModels; that’s it. It’s just that it’s more troublesome to use than before and you need to use it first. However, this also makes the project structure clearer, and all class libraries are organized under the namespace.

Time is limited, so I’ll write this much first. Hope you all like it.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/963125.htmlTechArticleFirst introduction to laravel5, laravel5 directory structure changes laravel5 first emphasizes the changes in the project directory structure, the difference from 4.2 is still It’s quite big, let’s talk about it item by item. The new directory structure will look like this...
Statement:
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