ThinkPHP framework knowledge, thinkphp framework
Php framework
1. Real project development steps:
Ii. Problems:
1. unreasonable division of labor for multi-person development projects (html php mysql)
2. The Code style is different and it is very difficult to maintain the code later.
3. The project life cycle is very short, and there is no continuity of the project life, resulting in waste of resources and waste of personnel
4. The project cannot meet the customer's needs very well, and the whole process is delayed.
Iii. Other related frameworks
1. The official framework released by zendframework zend php language company, heavyweight (with many features)
2. yii development framework for Chinese Americans, xue qiang, qiang, heavyweight framework, and pure OOP framework
3. CI CodeIgniter Lightweight Framework, fast development, flexible deployment
Iv. Framework:
A collection of code, including variables, functions, classes, constants, and many design patterns such as MVC, AR databases, and Singleton.
The framework can save us 50-60% of the workload, and we focus all our energy on the business layer.
5. Why is framework used?
(1) The framework helps us quickly, stably, and efficiently build a program system.
(2) The use of the Framework maximizes the maintainability, flexibility, and adaptability of the system to customer needs.
(3) The framework allows us to focus all our attention on the business layer without worrying about the underlying architecture of the program.
[Framework]
Thinkphp.cn
Thinkphp 3.2
[Framework project deployment]
Deploy a Shop project using the tp framework
Steps:
Create an entry file:
1. Create an entry file index. php under the ThinkPHP directory
2. When accessing the entry file, the system will automatically create the corresponding application directory file Shop.
3. Open the Home folder
[MVC mode]
M: Model data Model layer, responsible for data operations
V: View layer for displaying views
C: Controller to implement business logic
[Controller Access and route analysis]
Find the specified controller through the url address get parameter and make the corresponding method call request
Http: // URL/index. php? M = Module name & c = Controller & a = Method
The above url Information Code is not elegant and insecure.
The tp framework url can be composed of the following four types:
Specific url address Mode settings (configuration file ThinkPHP/Conf/convertion. php)
URL_MODEL = 0/1/2/3 represents four url address modes respectively
Config. php is the configuration file of our current project. We can modify this file to reach the configuration variable directory.
This file overwrites the configuration variables of convertion. php during system running.
Include "convertion. php ";
Include "config. php"; then, overwrite the file configuration variables introduced first.
Our system is compatible with the use of the url mode in 4
The system will automatically create a url address, which will be created and used according to the current mode.
Shortcut function U (); Create a url address
In url mode, we learned the following:
[Development and production modes]
Development and debugging mode: The system needs to load about 24 files index. php define ("APP_DEBUG", true );
Production Mode: the system only needs to load a very small number of seven files in the portal File
Defined in index. php: define ("APP_DEBUG", false );
Saves a lot of file development and shutdown system overhead, saving resources
To display trace information on the page, you need:
[Create a controller and corresponding method]
Controller is the core of the MVC mode. By default, tp has an Index controller:
There is an operation method in the Index Controller: Index
When we access the http: // localhost: 8080/Thinkphp/index. php entry file, the Index method under the Index controller is accessed by default.
If you want to create a controller Login:
1. Create a new Controller file LoginController. class. php In the \ Shop \ Home \ Controller folder.
Note: File naming rules are based on the hump method.
2. open the file and create the Controller Login class in it.
3. to customize the operation method, add a function Login () to the Controller Login class ():
In this way, we have completed the establishment of the controller and operation method. If you want to access the Login method under our Login controller just now:
4. If you want to call the template in the view layer in the controller:
In this way, an error will be reported during the next visit:
Cause: the template file is not created. At this time, we need to create the template file.
[Create a view template file]
The view template file is stored:
There is no template file in it
To access the Login method in the Login controller, first create a template folder corresponding to the Login controller, which corresponds to the Login controller:
Then, create a login.html template file under the Login folder to correspond to the Login method under the Login controller:
Write the code to be displayed in login.html:
Request again:
[Url case sensitivity settings]
The default value is not sensitive:
Set url sensitivity in config. php.
[Empty operation and empty controller processing]
Null operation: no operation method is specified.
Empty Controller: no controller is specified
Http: // URL/index. php/Home/User/login
Http: // URL/index. php/Home/User/hello empty operation
Http: // URL/index. php/Home/beijing/login empty Controller
Empty operation:
Generally, when a website is secure, no error message is prompted to the user.
An object (Controller) calls a method that does not exist.
In OOP, there are no methods for object calls. In terms of user experience, we can create a magic method in the class: function _ call ();
In tp, the Controller's parent class:
The parent class has a method:
Therefore, there are two solutions for empty operations:
① Create a method in the corresponding controller named "_ empty". All null operations of this controller will automatically execute this method. (Recommended)
② Create a template with the same name for the null operation name, and the system will automatically call
Empty controller:
Empty Controller: the specified class is not found when the Controller object is instantiated.
When to instantiate the Controller object: ThinkPHP/Library/Think/App. class. php
Note files:
Index. php entry file
Core ThinkPHP/ThinkPHP. php framework File
Core ThinkPHP/Library/Think. class. php framework File
ThinkPHP/Library/Think/App. class. php framework application file
In App. class. php, you can create a controller object and present the content of the method specified by the object call:
Empty controller solution: You can create another controller named EmptyController. class. php.
You only need to create a _ empty () method inside the controller.
Request again as follows:
[Project Group]
The system has a front-end user interface
The system also has a background for internal staff to use the maintenance platform.
The two are used to operate "controller", "view template", and "model.
For the convenience of system development and more reasonable code deployment, we should not mix the front and back-end files such as controllers and view views, but separate them in the physical structure.
Http: // URL/index. php/Home/controller/Operation Method access the Home controller and create operations
Http: // URL/index. php/Admin/controller/Operation Method access the controller and operation method of the Admin group
[System constant information]
Obtain system constant information:
If the parameter is set to true, the group displays:
[Cross-controller call]
When executing a controller, You Can instantiate another controller and access its specified method through an object.
Cross-controller call can save the workload of our code
There is an Info Operation Method in the Main controller.
To call other controllers, such as Login, We Can instantiate the Controller object and call the methods in it:
The object creation has a shortcut function for our use:
A ("[module/] Controller flag") instantiate the Controller object
R ([module/] Controller flag/Operation Method) instantiate an object and call the specified method at the same time
[Connection database configuration and Model data Model layer]
Convertion. php
Config. php
1. Configure database connection in config. php
2. Create a model
A) model itself is a class file
B) each data table in the database corresponds to a model file.
C) The simplest data model class
3. Field cache settings
During the execution of the tp framework, field information in the data table is used. You can use SQL statements to query "show colums from table". In terms of performance, you can cache fields, avoid repeated execution of SQL statements each time.
4. You can customize the current model as needed.
InstantiationModelThree methods:
A) $ goods = D ("Goods ");
B) This $ goods is the object of the parent class Model, but the operated data table is still sw_goods.
C) $ obj = D (); instantiate the Model object. There is no specific operation data table, which is consistent with the M () method.
A) instantiate the parent class Model.
B) You can directly call the attributes in the parent Model to obtain database-related operations.
C) a custom model is an empty shell and there is no need to instantiate a custom model.
D) $ obj = M ('data table flag'); instantiate the Model object and operate the specific data table
$ Obj = D (FLAG );
$ Obj = D ();
$ Obj = M (FLAG );
$ Obj = M ();
Differences between D () and M () methods:
The former is the simplified method for new operations in tp3.1.3;
The latter is used to instantiate the Model parent class.
Both define ThinkPHP/Common/functions. php In the function library file.
Note: if there is no corresponding model file class, you can also directly instantiate the model object for operations.
Both the D () and M () methods can be instantiated to operate a data table without a specific model file.
[Data Query]
Select () is a specific method of the data model to obtain data information about the data table.
Returns a two-dimensional array of all data in the current data table.
$ Obj = D (); create an object
$ Obj-> select (); query data
Select field, field from table name where condition group field having condition order sort limit;
SELECT % DISTINCT % FIELD % FROM % TABLE % JOIN % WHERE % GROUP % HAVING % ORDER % LIMIT % UNION % COMMENT %
$ Obj-> field (field, field); query a specified field
$ Obj-> table (data table); set a specific operation data table
$ Obj-> where (parameter); the parameter is the condition information behind the where clause of a normal SQL statement.
Example: ("goods_price> 100 and goods_name like '3% '")
$ Obj-> group (field); queries by field group
$ Obj-> having (parameter condition); having condition setting
$ Obj-> order ('price desc/asc ') Sort Query
$ Obj-> limit ([offset,] number of entries) limit the number of queried entries
The specific condition settings in the SQL statement are embodied in the tp framework model as specific method operations.
The above method is theoretically the corresponding method of the parent class Model.
Method for the parent class model: field () where () limit ()
There are also some methods in the _ call () automatic call function: table () group () order () having ()
In the _ call () magic method, the system checks whether the current execution method is an element of the method attribute. If it exists, the system executes the method.
The preceding methods use multiple conditions for display at the same time (and there is no sequence requirement)
$ Obj-> limit (5)-> field ('Id, name')-> order ('price asc ')-> table ('sw _ goods ') -> select ();
The execution of the preceding methods has no sequence requirement. After execution of many methods, the specific parameters are assigned to the options attribute of the model, and the SQL statements are assembled according to options.
$ Info = $ goods-> where ()-> field (field)-> select ();
Select () method
1. Returns a two-dimensional array.
2. Return all data table information
3. PASS Parameters to this method
A) select (30) query records whose primary key value is 30
B) select ("10, 12, 14") queries records whose primary key values are in the range of 10, 12, and 14.
4. find () if the query result has only one information, using select () will return a two-dimensional array.
For convenience, we want to return a one-dimensional array. In this case, we can use the find () method.
5. Set the query conditions in the having () method and where ().
6. Related Aggregate functions count () sum () avg () max () min ()
The above aggregate function is the last called method.
The preceding methods can be used in combination with specific conditions.
For example, $ goods-> where ('goods _ price> 100')-> count (); Total number of items greater than 1000 yuan
[Add Data]
Add () This method returns the primary key id value of the new record to be added.
Add data in two ways
1. Add data in array Mode
$ Goods = D ("Goods ");
$ Arr = array ('goods _ name' => 'iphone5s ', 'goods _ weight' => '123 ');
// Note: goods_name and goods_weight are the field names in the data table.
$ Goods-> add ($ arr );
2. Add data in AR Mode
A) ActiveRecord active records
B) AR specifies the relationship between the program and the database.
C) What is AR:
D) ① A data table corresponds to a class model
E) ② an object of the corresponding class of a Data Record
F) ③ specific attributes of each field on the object
G) the AR of the tp framework is false.
$ Goods = D ("Goods ");
$ Goods-> goods_name = "htc_one ";
$ Goods-> goods_price = 3000;
$ Goods-> add ();
The preceding two methods: array, AR, and add must return the primary key id value of the new record.
Collection Form data warehouse receiving operation]
Note: One add controller implements two logics. One is to display the add page, and the other is to add content to the database.
Note: If the primary key value is repeated, this error will cause the error () method to directly throw an error message without redirecting to the page. This is a new version problem. If you want to redirect, find
[Data modification operation]
Save () to modify data and return the number of affected records
There are two methods to modify data, which are similar to adding data (array and AR)
1. array Mode
A) $ goods = D ("Goods ");
B) $ ar = array ('goods _ id' => 100, 'goods _ name' => 'lenovo phone', 'goods _ price' => 1200 );
C) $ goods-> where ('goods _ id> 50')-> save ($ ar );
2. AR Mode
A) $ goods = D ("Goods ");
B) $ goods-> goods_id = 53;
C) $ goods-> goods_name = "Samsung mobile phone ";
D) $ goods-> goods_price = 2000;
E) $ goods-> where ('goods _ price> 10000 ')-> save ();
If the preceding two methods are feasible, you must modify all the data.
The preceding SQL statements are technically feasible and not applicable to the business (accident)
The tp framework has intelligent considerations. SQL statements in the above cases are not allowed to be executed.
How to execute:
① Clearly tell the system that the SQL statement is updated
② You can set where to update SQL statements.
Save () method Return Value
0: No problem before and after execution
Natural Number: Number of affected records
False: execution failed
Data modification implementation:
Route parameters to an operation method
Http: // URL/index. php/module/controller/method upd/variable name 1/value/variable name 2/value/variable name 3/value
The preceding routes pass three parameters to the specified operation in the get form.
The $ _ POST method is also supported.
When receiving the information of the three parameters, you can use $ _ GET to receive the information.
Example: $ _ GET ['variable name 1'];
The preceding parameter information is too straightforward and insecure. You need to use the following method to receive the get parameter information according to the framework rules.
Http: // URL/index. php/Admin/Goods/upd/name/tom/age/25/addr/beijing
Function upd ($ name, $ age, $ addr ){
$ Name;
$ Age;
$ Addr;
}
If the parameters are not transmitted according to the Rules during the request, access to the current method is prohibited.
(Unless the parameter has a default value)
To modify product information, follow these steps:
[Delete data and execute native SQL statements]
Delete () returns the number of affected records
$ Goods-> delete (30); delete records whose primary key value is 30
$ Goods-> delete ("10, 12, 13"); delete three records whose primary key value is 10 12 13
$ Goods-> where ("goods_id> 60")-> delete () delete all the matching records
Execute native SQL statements
$ Goods = D ("Goods ");
$ SQL = "select * from sw_goods ";
$ Rst = $ goods-> query ($ SQL );
$ SQL = "select goods_category_id, avg (goods_price) from sw_goods group by goods_category_id having avg (goods_price)> 1000 ";
$ Goods-> query ($ SQL );
$ SQL = "update sw_goods set goods_name = 'htc _ two' where goods_id = 100 ";
$ Goods-> execute ($ SQL );
Form Verification]
Javascript
Jquery
Form verification through the tp framework on the server side
Username, password, repeated password, email, qq, mobile phone number, hobbies, education
Procedure:
[Tp verification code supported]
ThinkPHP/Library/Think/Verify. class. php
$ Verify = new namespace Verify ();
$ Verify-> entry (); generate a verification code
A separate method to generate a verification code
Use in the template:
Verification Successful:
[Session and Cookie]
Session operations (cookies) in the tp framework)
// Set session (name, value, effective time)
// Get the session (name)
// Session (name, null) deletes the specified session
// Session (null) Clear all sessions
[Data paging using the tp framework]
1. Where we place third-party class libraries:
In the current module (Home) directory, the root of the class library namespace in the module is named by the module name
In the ThinkPHP/Library/directory, the root namespace isThinkPHP/Library
2.
InThinkPHP/Library/Think/
There are many class libraries for our use below
3. class naming rules: a namespace is required. The class file name is Page. class. php.
4. instantiate the paging class in the controller:
Template page:
[Tp framework Extension function library]
Three locations:
Write the custom method in the file.
[Chinese Garbled text for uploading tp framework files]
In windows:
In ThinkPHP/Library/Think/Upload/Driver/Local. class. php
Row 83rd changes $ filename to iconv ('utf-8', 'gb2312', $ filename)