First introduction to laravel5, laravel5_PHP tutorial
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.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

In PHPOOP, self:: refers to the current class, parent:: refers to the parent class, static:: is used for late static binding. 1.self:: is used for static method and constant calls, but does not support late static binding. 2.parent:: is used for subclasses to call parent class methods, and private methods cannot be accessed. 3.static:: supports late static binding, suitable for inheritance and polymorphism, but may affect the readability of the code.

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.
