0xx_PHP_TP framework

ThinkPHP framework

Today target (daily tasks)

ThinkPHP5 frame 1 can be mounted and the familiar common directory structure

2 controller can be used ThinkPHP5 frame

3 module can command line to create directories and files

4 can be used ThinkPHP5 Request frame request class

5 render template can be

I. Framework Overview

1. What is the framework

Frame is some code classes, methods (functions), variables, constants set, the code is a functional structural code (service code not). Business Code is actually a specific number of modules CRUD logic code.

Development projects using the framework, there is ease of code reuse, the development of high efficiency, good code specification for function expansion and the like.

2, php frameworks in the mainstream

①Zend Framework framework, PHP official framework.

②YII framework, also known as easy to frame.

③Symfony framework.

④Laravel framework, market use more.

⑤Codelgniter framework, referred to as the CI framework.

⑥ThinkPHP framework, referred to as the TP Framework, commonly Version: 3.2.3 and version 5.0 *.

ThinkPHP people to develop their own framework. There are Chinese official website, Chinese help documentation, Chinese communities, as well as rich resources of Baidu search. So ThinkPHP well suited as an entry-level development framework.

Most of these frameworks are based on MVC design and object-oriented.

mvc:

M: model model, business data processing, database and do interact.

V: view view, display html page, the user can see and interact with the page.

C: Controller controller, receives the request, call processing data model, view call display page.

Entire web applications, divided into three parts model, view, controller.

Two, ThinkPHP frame mounting

1. Download and unzip the frame

Download: http://www.thinkphp.cn

img

After downloading unzip to a working directory

2, the virtual host configuration

① configured through phpStudy the "site domain management" or directly modify the apache virtual host configuration file,

The site domain names point to public directory under the project directory

② DNS, modify the hosts file

A domain name is as follows: multiple domain names can be written on the same line, separated by a space

127.0.0.1 tpshop.com www.tpshop.com

③ restart apache, browser access to the configuration of a virtual site http://www.tpshop.com

See the above screen, indicating that the installation was successful framework.

apache configuration reference (not copy):

<VirtualHost *:80>
    DocumentRoot "E:\phpStudy\WWW\tpshop\public"
    ServerName www.tpshop.com
    ServerAlias tpshop.com
  	<Directory "E:\phpStudy\WWW\tpshop\public">
      	Options FollowSymLinks ExecCGI
        AllowOverride All
        Order allow,deny
        Allow from all
        Require all granted
  	</Directory>
</VirtualHost>

Three, TP frame base

1, the directory structure (focus)

(See manual - basis - the directory structure)

 1.project  应用部署目录
 2.├─application           应用目录(可设置)
 3.│  ├─common             公共模块目录(可更改)
 4.│  ├─index              模块目录(可更改)
 5.│  │  ├─config.php      模块配置文件
 6.│  │  ├─common.php      模块函数文件
 7.│  │  ├─controller      控制器目录
 8.│  │  ├─model           模型目录
 9.│  │  ├─view            视图目录
10.│  │  └─ ...            更多类库目录
11.│  ├─command.php        命令行工具配置文件
12.│  ├─common.php         应用公共(函数)文件
13.│  ├─config.php         应用(公共)配置文件
14.│  ├─database.php       数据库配置文件
15.│  ├─tags.php           应用行为扩展定义文件
16.│  └─route.php          路由配置文件
17.├─extend                扩展类库目录(可定义)
18.├─public                WEB 部署目录(对外访问目录)
19.│  ├─static             静态资源存放目录(css,js,image)
20.│  ├─index.php          应用入口文件
21.│  ├─router.php         快速测试文件
22.│  └─.htaccess          用于 apache 的重写
23.├─runtime               应用的运行时目录(可写,可设置)
24.├─vendor                第三方类库目录(Composer)
25.├─thinkphp              框架系统目录
26.│  ├─lang               语言包目录
27.│  ├─library            框架核心类库目录
28.│  │  ├─think           Think 类库包目录
29.│  │  └─traits          系统 Traits 目录
30.│  ├─tpl                系统模板目录
31.│  ├─.htaccess          用于 apache 的重写
32.│  ├─.travis.yml        CI 定义文件
33.│  ├─base.php           基础定义文件
34.│  ├─composer.json      composer 定义文件
35.│  ├─console.php        控制台入口文件
36.│  ├─convention.php     惯例配置文件
37.│  ├─helper.php         助手函数文件(可选)
38.│  ├─LICENSE.txt        授权说明文件
39.│  ├─phpunit.xml        单元测试配置文件
40.│  ├─README.md          README 文件
41.│  └─start.php          框架引导文件
42.├─build.php             自动生成定义文件(参考)
43.├─composer.json         composer 定义文件
44.├─LICENSE.txt           授权说明文件
45.├─README.md             README 文件
46.├─think                 命令行入口文件

2, the configuration file (focus)

(See Manual - Configuration)

① three-level configuration file:

A main frame profile (profile convention) thinkphp / convention.php

Apply common configuration file application / config.php, application / database.php into force for the entire application

Module configuration file application / module directory /config.php effect on the current module

② Other notes:

Configuration file format return array (key-value pair);

Loading order: a main frame profile "public profile Application" module configuration file

Configuration files take effect sequence: after loading the entry into force (configuration items previously loaded configuration items will be covered)

If you want to configure it manually, do not modify the general framework itself is the main configuration file,

It is configured in the application or the module configuration file.

3, function files

Framework helper file thinkphp / helper.php

Application of a public function file application / common.php

Module function file application / module directory /common.php

Generally not recommended to directly modify thinkphp / helper.php

4, development specification (understand)

TP frame coding standard: see manual - basis - the development of norms

img

Extended: PSR code specifications: https://www.kancloud.cn/thinkphp/php-fig-psr/3139

img

5, the request lifecycle

Lifecycle Framework, which is requested to perform the process:

img

Four, TP frame controller

1, the controller suffix

Open the configuration file application / config.php, the following configuration

'controller_suffix' => false,

It represents the default controller no special suffix. For example Index controller, a file named Index.php

If you need to set up, it can be set (we do not need such a set)

'controller_suffix' => 'Controller',

It indicates that the controller to Controller suffix. For example Index controller, a file named IndexController.php

2, the definition of the controller

(See Manual - Controllers - The controller is defined)

1) define the location and naming rules

Defined positions: application / module directory under / controller / directory

Naming: Controller name (first letter capitalized) + (Controller suffix, the default is no) + .php

Default: Index controller Index.php

User controller User.php

Test controller Test.php

Example:

img

2) write controller

① declare the namespace namespace app \ modules directory name \ controller

② introducing controller base class (optional) use think \ Controller; think namespace is the base class Controller Controller

③ define the current controller class, the base class inherits the controller (optional)

Example: defining a test controller Test.php

img

Namespace 3, frame

PHP namespace itself is there, and to prevent naming conflict.

Namespace TP frame, usually linked directory.

Reason: TP automatic loading mechanism, namespace class will be loaded as part of the path.

img

TP namespace to use:

① declare the namespace using the namespace keyword

② the introduction of the specified class using the use keyword namespace \ class name

③ fully accessed using the formula defined class \ complete namespace \ class name (inheritance and instantiation)

If a class has no namespace, use \ class name

4, url access

(See manual - Architecture --URL access)

ThinkPHP5.0 framework, using the url PATH_INFO way of access by default.

Example: http://www.tpshop.com/index.php/Index/Test/index/page/10

Format: HTTP: // domain / entry file / module / controller name / Title Operation / parameter name / value parameter

Hidden entry file written: HTTP: // domain / module / controller Name / Operation name / parameter name / parameter value

Apache need to be set (manual - architecture --URL access, manual - Deployment --URL rewrite)

img

PHPStudy need to use .htaccess files in public directories, plus behind index.php?

After using Apapche rewriting mechanism for entrance hidden files, if coupled with .html suffix url entire back, the whole url looks like static pages visited. This is called "pseudo-static."

5, debug mode

(See manual - error and debug - debug mode)

By default, if the code is wrong (such as the controller name is misspelled), the following error occurs:

Error description is vague, inconvenient, error debugging. This mode is often called the "deployment mode" (production model).

You can set the framework for the development phase to debug mode for easy error debugging:

Modify the project directory \ application directory \ config.php

When you turn on debug mode, the error message in the following format:

It will prompt detailed error information and error position (reference position).

Line with respect to the environment (the period after completion of development), is called the deployment patterns or production mode.

Fifth, create a module

1, create a foreground and background module

A typical application is composed of multiple modules (usually the front desk and back office management system website module module), these modules are usually in a subdirectory of the application directory, and each module has its own separate configuration files, common files and library files.

We create home (foreground) and admin (back) two modules to the project:

2, set the default access module

Open the configuration file application / config.php, the following configuration

'default_module' => 'index',

It indicates the default access module to module index

You can change the default module to module home

'default_module' => 'home',

Sixth, the command line to create the module directory and file

In the project root directory (the directory where the file think) Run

1, the command line to create the module directory

(See Manual - Command Line - to automatically generate directory structure)

It can generally be generated automatically by the command module directory

php think build --module 模块名

For example: Create test module directory, execute the command php think build --module test can be. (Module name in lowercase)

2, the command line to create a controller

(See Manual - Command Line - Create a class library file)

It can often be created automatically by the command controller

php think make:controller 模块名/控制器名 
php think make:controller 模块名/控制器名 --plain

Plus --plain parameter indicates no air controller class method. Otherwise, the controller class will bring their own methods.

For example: Create a home controller module Index, execute the command php think make: controller home / Index can be.

Note: The controller name capitalized.

3, the command line to create a model

(See Manual - Command Line - Create a class library file)

Usually can automatically create a model using the following command

php think make:model 模块名/模型名

For example: Create a home module User model, execute the command php think make: model home / User can.

Note: The model name capitalized.

Seven, Request Request Class

1, to obtain input variables

(See manual - request - Input variables)

To get the current request information, we can use \ think \ Request class

$request = \think\Request::instance();

Or use a helper function

$request = request();

You can also get get variable or variables alone post

Request::instance()->get();
Request::instance()->post();
input('get.');
input('post.');

Code Example:

Browser to access the results:

Special Instructions: routing variables and get variables

http://www.tpshop.com/home/test/index/id/100?page=10

param method gets all parameters (id, page)

get method can only get? behind the request parameter string (page)

route only method to obtain parameter (id)? route in front of the

2, parameter binding

(See manual - request - parameter binding)

The method of binding is the URL address parameter (or routing address) of the method of operating the variable as a parameter passed directly.

Example of use: home controller module Test read method, the declared parameter $ id

Visit the url, id parameter passed http://www.tpshop.com/home/test/read/id/100

effect:

3, dependency injection

(See Handbook - Request - dependency injection)

Dependency injection: Briefly, to use another time-dependent class B class A, class B does not directly instantiated in the class A, but the first instance of class B and then passed as a parameter class A.

Framework uses:

Principle Analysis:

Supplement: Request request class encapsulates a lot of requests and related methods, as detailed in the manual - the request (see more)

summary:

Any method can be found receiving a request parameter

//1.获取请求对象  
$request = request();
$request = \think\Request::instance();
$request = $this->request; //仅限于继承了底层控制器的情况下
public function save(Request $request)  //依赖注入
   //2. 接收请求参数 param方法
    $params = $request->param();
	$params = input();
	$params = request()->param();
	$id = $request->param('id');
	$id = input('id');
	public function edit($id)//参数绑定

Eight, ThinkPHP frame view

1, the view composition

View view class (inherited custom template engine, Smarty functions and similar)

HTML template files

2, custom templates

(See Manual - Templates - template positioning)

In order to more effectively manage the template file, ThinkPHP template file directory division, the default template file defines rules: view the directory / Controller name (lowercase) / operating name (lowercase) + template suffix

The default view is the module directory view directory view the default file extension framework is .html.

For example, the template definition home controller module Index index method to call to view / index / index.html

3, template rendering

(See manual - View - template rendering, manual - View - template assignment)

In the control process,

The first: Use assign a template assignment method, using a fetch method template rendering.

The second: use the helper function view (), rendering and template assignment.

Example of use:

NOTE: output variable values ​​in the template: Template variable $ {name}

Nine, the background template and make binding framework

Template integration ideas:

① page access path is determined (block, controller, method)

② new controller method corresponding template in the method call

③ template will move to the next page view corresponding directory (create a subdirectory)

④ Move static resource files to the public / static / admin directory

⑤ modify the template file static resource path

Distribution page:

Login page Login controllers login method login.html

Home Index controller index method index.html

Product List Goods controller index method goods_list.html -> index.html

Commodity Goods create new methods goods_add.html controller -> create.html

Product Review Goods edit controller Method goods_edit.html -> edit.html

Administrators List Manager controller index method manager_list.html -> index.html

Administrators create new Manager controller method manager_add.html -> create.html

Manager administrator to modify the controller edit method manager_edit.html -> edit.html

...

1, the template layout

(See Manual - Templates - Template Layout)

Use layout templates, page templates is to have more of a common code to be extracted, placed in a public location development and maintenance

Benefits: The same code maintains only one, reducing the workload of the code

Global background layout setup steps:

① modify the configuration file application / admin / config.php, add the following settings

'template'  =>  [
    'layout_on'     =>  true,//开启布局
    'layout_name'   =>  'layout',//布局文件名称
]

② static resource files moved to / public / static / admin directory

③ In the application / admin / view directory, create layout.html

The common background page header, the code extraction layout.html the bottom, placed in an intermediate position a special string "{_ the CONTENT _}", indicates the position, replacing the original contents of the page to be accessed.

layout.html file, leaving only the pages of all the public of the relevant css and js code, modify static resource path

Note: must not direct all css and js are placed in layout.html.

Note: TP framework, static resource path template, you can not use relative paths ./ must be used with / at the beginning of the path.

④ temporary closure template layout

Global layout settings, all to take effect for all pages.

Special pages (page layout does not require the use of), you can control method, temporarily close the template layout.

$this->view->engine->layout(false);

For example, the login page, do not need to use layout, see "3, backstage login page."

2, back home

① page access path is determined (block, controller, method)

admin module controller index Index Method

② new controller method corresponding template in the method call

<?php
namespace app\admin\controller;

use think\Controller;

class Index extends Controller
{
	public function index()
	{
		return view();
	}
}

③ moves to the next page template view corresponding directory

index.html => application/admin/view/index/index.html

④ modify the template file

Reservations page unique static resource files, as well as the main part of the code

Modify the template file static resource path

Note: If the page does not display, you can consider deleting the cache runtime directory

3, background login page

① page access path is determined (block, controller, method)

Controller module login login method admin

② new controller method corresponding template in the method call

Note: The background of the login page, do not need to use layout

③ moves to the next page template view corresponding directory

Login.html will move to the next application / admin / view / login / directory

⑤ modify the template file static resource path

Modify the application / admin / view / login / login.html

Note: You can also use _ the STATIC _ instead of / static static resource path (manual - View - Output replacement)

4, other pages

Repeat steps ①②③⑤

operation

The following Template Integration

Product List Goods controller index method goods_list.html -> index.html

Commodity Goods create new methods goods_add.html controller -> create.html

Product Review Goods edit controller Method goods_edit.html -> edit.html

Administrators List Manager controller index method manager_list.html -> index.html

Administrators create new Manager controller method manager_add.html -> create.html

Manager administrator to modify the controller edit method manager_edit.html -> edit.html

to sum up:

1. Install deployment framework, familiar with the directory structure (application public)

2. The controller is defined, the access controller (hidden file entry, format PATH_INFO url) to access to the designated control method

3. Command-line operation (creation module creates controller class) (environment variables)

4.Request using basic request object - reception parameters (written using one skilled)

5. Integration template (template layout)

Guess you like

Origin www.cnblogs.com/xeclass/p/12657536.html