Table of Contents
First introduction to laravel5, laravel5
Home Backend Development PHP Tutorial First introduction to laravel5, laravel5_PHP tutorial

First introduction to laravel5, laravel5_PHP tutorial

Jul 13, 2016 am 10:05 AM

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 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)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

See all articles