search
HomeBackend DevelopmentPHP TutorialFirst introduction to laravel5_PHP tutorial

First introduction to laravel5_PHP tutorial

Jul 13, 2016 am 10:05 AM
First acquaintancereleasedomesticCompareat presentRelatednetmaterial

First introduction to laravel5

laravel5 has been released. At present, there is relatively little domestic related information, so I can only go over the wall and go to the official website to take a look first. I have initially summarized some changes, and I just want to Write it down.

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
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 in 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, classes are created in the Middleware directory and configured 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:

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

The code is as follows:

php artisan route:cache

can be easily generated, or you can use

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 presence of 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:

The code is as follows:


# 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']),
]);
}
}

 

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

 

代码如下:


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());
}

 

可以看到,表单验证的业务逻辑仅仅一行:

 

代码如下:


$validator = $this->registrar->validator($request->all());

 

整个控制器的代码显得干净易读,我们可以把很多通用的业务逻辑封装成service,比不伦不类地直接封装在控制器类好。

模型

models目录不见了,因为不是所有应用都需要用到数据库的,所以laravel5默认不提供该目录可以理解,而且由于提供了 App 这个namespace,所以我们可以自己在 App/ 下创建 Models 目录,其中所有模型类都声名namespace AppModels;即可,只是使用上比以前麻烦一些,需要先use,不过这样也使得项目结构更加清晰,一切类库都在命名空间的组织之下。

时间有限,先写这么多吧。希望大家能够喜欢。

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/962924.htmlTechArticle初识laravel5 laravel5发布了,目前国内相关资料还比较少,只能先翻墙去官网先看看了,初步总结了一些变化,就想写下来。 目录结构变化...
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
What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

What is the importance of setting the httponly flag for session cookies?What is the importance of setting the httponly flag for session cookies?May 03, 2025 am 12:10 AM

Setting the httponly flag is crucial for session cookies because it can effectively prevent XSS attacks and protect user session information. Specifically, 1) the httponly flag prevents JavaScript from accessing cookies, 2) the flag can be set through setcookies and make_response in PHP and Flask, 3) Although it cannot be prevented from all attacks, it should be part of the overall security policy.

What problem do PHP sessions solve in web development?What problem do PHP sessions solve in web development?May 03, 2025 am 12:02 AM

PHPsessionssolvetheproblemofmaintainingstateacrossmultipleHTTPrequestsbystoringdataontheserverandassociatingitwithauniquesessionID.1)Theystoredataserver-side,typicallyinfilesordatabases,anduseasessionIDstoredinacookietoretrievedata.2)Sessionsenhances

What data can be stored in a PHP session?What data can be stored in a PHP session?May 02, 2025 am 12:17 AM

PHPsessionscanstorestrings,numbers,arrays,andobjects.1.Strings:textdatalikeusernames.2.Numbers:integersorfloatsforcounters.3.Arrays:listslikeshoppingcarts.4.Objects:complexstructuresthatareserialized.

How do you start a PHP session?How do you start a PHP session?May 02, 2025 am 12:16 AM

TostartaPHPsession,usesession_start()atthescript'sbeginning.1)Placeitbeforeanyoutputtosetthesessioncookie.2)Usesessionsforuserdatalikeloginstatusorshoppingcarts.3)RegeneratesessionIDstopreventfixationattacks.4)Considerusingadatabaseforsessionstoragei

What is session regeneration, and how does it improve security?What is session regeneration, and how does it improve security?May 02, 2025 am 12:15 AM

Session regeneration refers to generating a new session ID and invalidating the old ID when the user performs sensitive operations in case of session fixed attacks. The implementation steps include: 1. Detect sensitive operations, 2. Generate new session ID, 3. Destroy old session ID, 4. Update user-side session information.

See all articles

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

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.