thinkphp Framework Knowledge

Source: Internet
Author: User
Tags php language php define php framework php mysql



PHP Framework



First, the real project development steps:


    1. Many people at the same time develop projects, collaborative development projects, reasonable division of labor, Efficiency has improved (code style is different, division of labor is not good)
    2. Testing phase
    3. On-line operation
    4. Maintenance, modification, and upgrade of the project (individual maintenance project, very difficult, code style is not the same)
    5. Stable operation phase of the project
    6. Project stopped running (the old project staff have all left, the new development project)





Second, the question:



1. Multi-person development project, the Division of labor is unreasonable, (HTML PHP mysql)



2. Code style is not the same, late maintenance is very difficult



3. Project life cycle is very short, project life is not continuity, resulting in waste of resources, personnel waste



4. The project does not adapt well to customer needs, reaching.






Third. other relevant frameworks



1. Zendframework Zend PHP Language Company released the official framework, heavyweight (multi-function)



2. Yii American Chinese Development Framework, Xue Qiang, Qiang, heavyweight framework, pure OOP framework



3. CI CodeIgniter Lightweight framework, fast development, flexible deployment


    1. CakePHP foreign frame, heavyweight, slow
    2. Symfony Foreign Heavyweight Framework
    3. Thinkphp lightweight frame, Chinese frame, easy to get started





Fourth. What framework:



A bunch of code collection, inside there are variables, functions, classes, constants, there are many design patterns MVC, AR database, Singleton and so on.



The framework can save us the 50-60% of our work, and all of our energies are focused on the business level.






Fifth. Why the use of frames



(1) The framework can help us to set up the program system quickly, stably and efficiently.



(2) The system is enhanced by the use of the framework to maximize its maintainability, flexibility and adaptability to customer needs.



(3) The process of using the framework allows us to focus all of our attention on the business level without having to care about the underlying architecture of the program.






"Use Frame"



thinkphp.cn






thinkphp version 3.2















"Framework Project Deployment"



Deploy a shop project using the TP framework



Steps:



To create a portal file:



1. Create a portal file under the thinkphp directory index.php






2. Access to the Portal file system will automatically create the corresponding application directory file shop






3. Open the Home folder






"MVC pattern"



M:model Data Model layer, responsible for data manipulation



V:view view layer, responsible for displaying the view



C:controller Controller for business logic






"Controller access and routing resolution"



Locate 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 address information code is not elegant, not secure.






The TP frame URL address can be made up of the following four


    1. HTTP//URL/index.php?m=xx&c=xx&a=xx basic Get mode
    2. http:///index.php/module/Controller/operation method Path mode PathInfo
    3. http://module/Controller/operation method rewrite override mode
    4. HTTP//URL/index.php?s=/module/controller/method Compatibility mode





Specific URL address mode settings (config file thinkphp/conf/convertion.php)



Url_model = 0/1/2/3 represents four URL address modes respectively






Config.php is the configuration file for our current project, and we can modify the file to reach the directory of configuration variables.



This file will overwrite the convertion.php configuration variables during system operation.



Include "convertion.php";



Include "config.php"; After the introduction of the file to the first introduction of the file configuration variables to cover out






Our system is compatible with the use of 4 URL address mode



The system will sometimes automatically create a URL address, which will be created using the URL address according to the current schema



Shortcut function u (); Create a URL address






We learned the following from the URL address pattern:


    1. We learned the configuration variables (core configuration variable conversion.php, current application configuration variable config.php)
    2. The shortcut function u ("module/Controller/method") creates the corresponding URL address according to the parameter and URL pattern
    3. Adjust the frame mode to develop debug mode





"Development, production model"



Development Debug Mode: The system needs to load about 24 files index.php define ("App_debug", true);



Production mode: The system only needs to load very little about 7 files in the portal file



index.php defined in: Define ("App_debug", false);



Save resources by saving a lot of file development, shutting down the system overhead






To display trace information on the page, you need to be in your own configuration file:






"Controller and corresponding method creation"



The controller is the core of the MVC pattern, and TP has an index controller by default:






The index controller has an operation method: Index






When we access the http://localhost:8080/Thinkphp/index.php portal file, we will access the index method under the index controller by default.






If you want to create a controller yourself login:



1. Create a new controller file under the \shop\home\controller folder LoginController.class.php



Note: File naming rules, named according to the Hump method






2. Open the file, build the controller login class inside






3. If you want to customize the action 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 our login controller under the login method:






4. In the controller if you want to invoke the template in the view layer:






If you visit again, you will find an error:






Cause: The template file is not created and we are going to create the template file






"View Template file Creation"



The view template files are stored in the following locations:






There are no template files inside



If we want to access the login method in the login controller, we will 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 the login.html:






Then ask again:






"URL address case Settings"



The default is not sensitive:



Setting URL-case sensitivity in config.php









"NULL operation and NULL controller handling"



Empty operation: There is no specified action method



NULL controller: No controller specified



http +/URL/index.php/home/user/login



http://url/index.php/home/user/hello empty operation



HTTP//URL/index.php/home/beijing/login null controller


Empty operation:





General website Security considerations do not prompt users for any error messages



"Empty operation" essentially means that an object (Controller) calls itself a method that does not exist



In OOP, the object call itself does not exist methods, in the user experience is a good point of view, we can create a magic method inside the class: function __call ();






Inside the TP is the parent of the controller:









There is a method in the parent class:









So there are two solutions to an empty operation:



① in the corresponding controller to make a method, the name of "_empty", the controller's empty operation will automatically execute the method. (Recommended use)



② the name of the empty operation to make a template with the same name, the system will automatically call









NULL Controller:






NULL controller: The specified class was not found when instantiating the Controller object



When to instantiate a controller object: thinkphp/library/think/app.class.php



Memorize files:



index.php Portal File



Thinkphp/thinkphp.php Framework Core File



Thinkphp/library/think/think.class.php Framework Core File



thinkphp/library/think/app.class.php Framework application file



Inside the App.class.php include the Controller object creation, and the object invokes the specified method to render the content:






NULL controller processing scheme: You can make a controller, name EmptyController.class.php



It is only necessary to make a _empty () method inside the controller.








This request again:






"Project Grouping"



The system has the front user operation interface



The system also has backstage for the company internal personnel use maintenance platform



The two are used in the process of "controller", "View Template", "Model models" operation.



For system development convenience, and code deployment more reasonable, our controller, view view and so on before and after the file do not mix in, to the physical structure to separate









http://URL/index.php/home/Controller/operation method Access Home controller and make operation



http://URL/index.php/admin/Controller/operation method Access Admin group controller and how to



"System Constant Information"



Get System Constant Information:






If the argument is true, the display is grouped:









"Cross-controller call"



When a controller executes, it can instantiate another control and access its specified method through the object.



Cross-controller calls can save our code's effort



There is an info operation method in the main controller









To invoke in other controllers, such as login, we can instantiate the Controller object and invoke the method inside:









The object has shortcut functions for us to use:



A ("[Module/] Controller flag") instantiating the Controller object






R ([module/] Controller flag/action method) instantiating an object invokes the specified method at the same time






"Connecting the database configuration and model data models layer"



convertion.php



config.php



1. Make database connection configuration in config.php









2. Making model Models



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



The TP framework executes the field information in the data table, the SQL statement can query "show colums from Table", in performance consideration, you can cache the field, avoid repeating the SQL statement every time.



4. The current model model can be personalized according to the situation






instantiation of Model three ways to:


    1. $goods = new namespace Goodsmodel ();
    2. $goods = D (' model sign ');


a) $goods = D ("goods");



b) The $goods is the object of the parent model, but the data table of the operation is still sw_goods



c) $obj = D (); Instantiate the model object with no specific operational data tables, consistent with the M () method effect


    1. $obj = M ();


A) instantiation of the parent class model



b) You can directly invoke the properties inside the parent model to get database related operations



c) Custom model is an empty shell, there is no need to instantiate a custom model



d) $obj = M (' Data sheet sign '); Instantiate the model object and actually manipulate the specific data table



$obj = D (sign);



$obj = D ();



$obj = M (sign);



$obj = M ();



The difference between the D () and M () methods:



The former is a simplified method for new operation in tp3.1.3;



The latter is used to instantiate the model parent class



Both are defined in the function library file thinkphp/common/functions.php






Note: If there is no corresponding model model file class, you can also instantiate the model object directly for operation



Both the D () and M () methods can be instantiated to manipulate a data table that does not have a specific model class file.



"Data Query"



Select () is a specified method of the data model that can obtain data information for a data table



Returns a two-dimensional array of information, all data information for the current data table



$obj = D (); Creating objects



$obj Select (); Querying data



Select field, field from table name where Condition Group field having conditional order ordering limit limit bar number;



Select%distinct%%field%from%table%%join%%where%%group%%having%%order%%limit%%UNION%%COMMENT%






$obj->field (field, field); Querying a specified field



$obj->table (data sheet); Set up a specific action data sheet



$obj->where (parameter); The parameter is the condition information behind the normal SQL statement where



For example: ("Goods_price >100 and Goods_name like ' three '")



$obj->group (field); Group queries based on fields



$obj->having (parameter condition); Having conditional settings



$obj->order (' Price desc/asc ') sort query



$obj->limit ([offset,] number of bars) limit the number of bars queried






Inside the SQL statement, the specific conditions are set in the TP frame model, which is embodied in the concrete method operation.






The above method is theoretically the corresponding method of the parent model.



Parent model Specific Existence method: Field () where () limit ()



There are also methods in __call () to automatically invoke functions inside: Table () group () Order () having ()



In the __call () Magic method, you will determine whether the current execution method is the element information for the property of the method, and executes if it exists.






More than one method is to use multiple conditional displays at the same time (and no order required)



$obj, Limit (5)->field (' Id,name ')->order (' Price ASC '), table (' Sw_goods ')->select ();



Many of these methods do not have sequential requirements, and many of these methods are assigned to the model properties options, and finally the SQL statements are assembled according to options.






$info = $goods, where ()->field (field)->select ();



Select () method



1. Returns a two-dimensional array of information



2. Return all data table information



3. Passing parameters to the method



A) Select (30) query for record information with primary key value equal to 30



b) Select ("10,12,14") to query the primary key values in the 10, 12, 14 range of record information



4.find () If the result of our query has only one message, using Select () returns a two-dimensional array



For ease of use we would like to return a one-dimensional array, when you can use the Find () method






5.having () method sets the query condition, where () sets the query condition



6. Correlation aggregate function count () sum () avg () max () min ()



The above aggregation function is the last method to be called



The above method can be used in combination with the specific condition method



For example: $goods, where (' Goods_price >1000 ')->count (); Total number of items greater than $1000






"Data Add"



Add () This method returns the primary key ID value of the new record that was added



Two ways to implement data addition



1. Array mode Data add



$goods = D ("goods");



$arr = Array (' goods_name ' = ' iphone5s ', ' goods_weight ' = ' 109 ');



Note: Goods_name and goods_weight are field names in the data table



$goods, add ($arr);






2.AR Method for data addition



A) ActiveRecord active record



b) AR Specifies the relationship between the program and the database



c) What is AR:



d) ① a data table corresponding to a class model



e) ② An object of the corresponding class for a data record



f) ③ the specific properties of each field to the expected object



g) The AR of the TP frame is false



$goods = D ("goods");



$goods-goods_name = "Htc_one";



$goods-goods_price = 3000;



$goods, add ();



Both ways: Array, AR, and finally add to return the primary key ID value of the new record






"Collect form data inbound operations"


    1. Make a form
    2. Collect information through $_post
    3. Data collection is implemented through the Create () method, which automatically filters for illegal fields


Note: An add controller implements two logic, one is to play the Add page, and the other is to add content to the database









Note: If the primary key value repeats, this error will cause the error () method not to jump directly to the page, which is the new version of the problem, if you want to jump, find









"Data modification Actions"



Save () implements data modification to return the number of affected record bars



There are two ways to implement data modification, similar to adding (array, AR mode)



1. Array mode



a) $goods = D ("goods");



b) $ar = Array (' goods_id ' =>100, ' goods_name ' = ' Lenovo phone ', ' goods_price ' =>1200);



c) Save ($ar) $goods->where (' goods_id>50 ');



2.AR mode



a) $goods = D ("goods");



b) $goods goods_id = 53;



c) $goods-goods_name = "Samsung mobile";



d) Goods_price = 2000, $goods



e) $goods->where (' goods_price>10000 ')->save ();



The above two methods, if feasible, are to modify all the data



The above SQL statements are technically feasible and not feasible from the business (accidents)



The TP framework has intelligent considerations, and the above case of SQL statements is not allowed to execute.



How to perform:



① explicitly tells the system that the SQL statement was updated by update



② can set where to perform SQL statement update operations






Save () method return value



0: No problem, no change in data before and after execution



Natural number: Number of affected record strips



False: Execution failed






Data modification Specific implementation:



Passing parameters by route to an action method



HTTP//URL/index.php/module/controller/method upd/variable name 1/value/variable name 2/value/variable name 3/value



The above route is the three parameter information passed to the specified operation through get form



$_post mode can also be



Principle three parameter information received by $_get



Example: $_get[' variable name 1 '];






The above parameter information reception is too straightforward, unsafe, you need to follow the framework rules using the following method to receive the Get parameter information



http +/URL/index.php/admin/goods/upd/name/tom/age/25/addr/beijing



Function upd ($name, $age, $addr) {



$name;



$age;



$ADDR;



}



The above parameter is expressed, if the request is not followed by the rules to pass parameters, then the current method is forbidden to access.



(unless the parameter has a default value)






To modify a product information step:


    1. The modified item ID information is passed to the UPD operation in the Get form at the "Modify" button
    2. In the Upd method inside the form parameter $goods_id, receive the server to pass the GET variable goods_id
    3. Make hidden field goods_id in modify form, avoid TP frame prohibit Modify statement execution
    4. There are two logic inside the UPD operation method: Show form, collect form





"Data deletion and execution of native SQL statements"



Delete () returns the number of affected record bars



$goods, delete (30); Delete Record information with primary key value equal to 30



$goods, delete ("10,12,13"); Delete three records with primary key value equal to 10 12 13



$goods, where ("goods_id>60")->delete () delete eligible records





Executing native SQL statements
    1. Query statement () returns a two-dimensional array of information
    2. Add, modify, delete execute () returns the number of affected record bars


$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 have avg (goods_price) >10 00 ";



$goods->query ($sql);






$sql = "Update sw_goods set goods_name = ' Htc_two ' where goods_id=100";



$goods->execute ($sql);






"Form Validation"



Javascript



Jquery



Form validation via TP Framework on server side



User name, password, duplicate password, mailbox, QQ, mobile phone number, hobby, education



Specific steps:


    1. Create a form
    2. Form form data is collected through the Create () method (the validation feature requires that we must collect data through the Create () method)
    3. Custom data Model class implementation specific validation rules

















"TP Framework Verification code supports the use of"



thinkphp/library/think/verify.class.php



$verify = new namespace verify ();



$verify-entry (); Generate a verification code






A separate method to generate the verification code






Use in templates:






Verify success:






"Session and Cookie"



TP Framework about session operation (cookie)



Session (Name,value, effective time) Set session



Session (name) gets session



Session (Name,null) delete the specified session



Session (NULL) clears all session






"TP Framework for data paging"



1. Location of our third-party class library:



Under the current module (Home) directory, the root of the class library namespace in the module is named after the module name



thinkphp/library/directory, the root namespace isThinkPHP/Library



  2.InThinkPHP/Library/Think/下面有很多类库供我们使用



3. Naming rules for classes: To have a namespace, class file name Page.class.php









4. Instantiate the paging class in the controller using:






Template page:






"TP Framework extension function library"



Three positions:


    1. thinkphp/common/functions.php
    2. Application/common/common/function.php
    3. Module/common/function.php


Write a custom method in the file to






"TP frame File upload Chinese garbled problem"



Under the Windows operating system:



In thinkphp/library/think/upload/driver/local.class.php



The 83rd line $filename changed to Iconv (' utf-8 ', ' gb2312 ', $filename)



thinkphp Framework Knowledge


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.