How to use thinkphp
1. Project deployment
1. Virtual host deployment/local deployment
Remove public/index.php and change to /index.php in the root directory. Create the file index.php in the root directory of the website with the following content
<?php // 定义应用目录 define('APP_PATH', __DIR__ . '/apps/'); // 加载框架引导文件 require './thinkphp/start.php';
This is basically it. This is the simplest configuration.
2. Server deployment
The server deployment project file entrance is public. Advantages: Only outsiders can see the files in the public directory. Files at the same level as public are hidden on the external network. Such as: thinkphp, apps, extend, tests, vendor. The simpler meaning is that the content under these files cannot be accessed through the domain name, but it does not affect the use of the framework.
2. Create modules (automatically generate modules)
My project is deployed in the local www/thinkphp directory. Before doing so, consider clearly how many modules you will need to complete your project.
Start the example
1. Create three modules: Common (public module), Home (front-end module), and Admin (back-end module). Public modules are essential.
In the case of modification, it is index.php under public. Open it like this
// 定义应用目录 define('APP_PATH', __DIR__ . '/../application/'); // 加载框架引导文件 require __DIR__ . '/../thinkphp/start.php';
Add these two sentences at the end
$build = include '../build.php'; // 运行自动生成 \think\Build::run($build);
build.php configuration (automatic Generate directory) Manual reference: http://www.kancloud.cn/manual/thinkphp5/118021
There is a build.php file in the root directory of the project. After opening it, you will see something like this:
<?php return [ // 生成应用公共文件 '__file__' => ['common.php', 'config.php', 'database.php'], // 定义demo模块的自动生成 (按照实际定义的文件名生成) 'demo' => [ '__file__' => ['common.php'], '__dir__' => ['behavior', 'controller', 'model', 'view'], 'controller' => ['Index', 'Test', 'UserType'], 'model' => ['User', 'UserType'], 'view' => ['index/index'], ], // 其他更多的模块定义 ];
Then we add the file name we need here. The demo given can be commented out directly, as follows:
<?php return [ // 生成应用公共文件 '__file__' => ['common.php', 'config.php', 'database.php'], //公共模块目录 'common' => [ '__file__' => ['common.php'], '__dir__' => ['controller', 'model','lang'], 'controller' => ['Index'], 'model' => ['Base'], ], // Index模块 'home' => [ '__file__' => ['common.php'], '__dir__' => ['behavior', 'controller', 'model', 'view','lang'], 'controller' => ['Index'], 'model' => ['Test'], 'view' => ['index/index'], ], // Admin 模块 'admin' => [ '__file__' => ['common.php'], '__dir__' => ['behavior', 'controller', 'model', 'view','lang'], 'controller' => ['Index'], 'model' => ['Test'], 'view' => ['index/index'], ], ];
1) Among them, SITE_PATH and RUNTIME_PATH are both used later, and all take precedence. Put it in index.php for easy calling later.
2) These two things should be used together
$build = include './build.php'; // 运行自动生成 \think\Build::run($build);
Related recommendations: "ThinkPHP Tutorial"
3. Create a base Class
Before starting, you must first set up the "base class". Why? For example, if you want to access the controller related to the member center, do these controllers need to have a "login restriction" to allow access to the member-related controller? The role of the base class comes out.
1. Create three major base classes
Original base class
Location: thinkphp\apps\common\controller\base.php
Function: base The content under the module, Index module, and Admin module can all be called.
Code:
<?php /** * 原始基类 * */ namespace app\Common\controller; use think\Controller; class Base extends Controller{ public function _initialize() { parent::_initialize(); echo '原始基类'; } public function test1(){ return 'test1'; } }
Index module base class
Location: thinkphp\apps\common\controller\base.php
Function: Under the Index module Controllers must "inherit the base class" and "call the base class".
Code:
<?php /** * 前端基类 * */ namespace app\index\controller; use app\Common\controller\Base; class IndexBase extends Base { public function _initialize() { parent::_initialize(); } public function index() { } }
Admin module base class
Location: thinkphp\apps\common\controller\base.php
Function: Under the Admin module Controllers must "inherit the base class" and "call the base class".
Code:
/** * 后台首页 * */ namespace app\Admin\controller; use app\Admin\controller\AdminBase; class Index extends AdminBase { public function _initialize() { parent::_initialize(); } public function index() { return $this->fetch(); } }
(User module base class, if there is a member, this must also be created)
The main purpose of creating a base class is to "inherit" with "call".
4. Set the template path
The default template path is in the module/view file. If you think this is not convenient to manage and want to set it in the Template directory, you can do so.
Template parameters, other parameters that can be affected are the config.php template->view_path parameters under the current module.
Practical operation
1. Configure shared parameters
Set some parameters in apps/config.php to facilitate calling config.php under the Index or Admin module.
apps/config.php, add some parameters.
'template' => [// 模板路径 'view_path' => 'template/', // 就是这里 /** * 前台文件配置 * Author: MR.zhou * */ 'index' => [ // 模快名称 'model_name' =>'index', // 默认模板文件名称 'default_template' => 'default', // 这里可以切换模块下的默认模板名称 ], /** * 后台文件配置 * Author: MR.zhou * */ 'admin'=>[ // 模快名称 'model_name' =>'admin', // 默认模板文件名称 'default_template' =>'default', // 这里可以切换模块下的默认模板名称 ],
2. Set template parameters
index/config.php
'template'=> [ // 模板路径 'view_path'=> config('template.view_path').config('index.model_name').'/'.config('index.default_template').'/', ],
admin/config.php
<?php //配置文件 return [ // 模板配置 'template' => [ // 模板路径 'view_path' => config('template.view_path').config('admin.model_name').'/'.config('index. default_template').'/', ], ];
Extension:
1. Template suffix view_suffix, its impact
http://localhost/thinkphp/index/news/index/id/1212
http://localhost/thinkphp/index/news/ index/id/1212.html
5. Configure the data folder
If you look at the various files under the project and feel a mess, you can The following configurations are possible.
Configure the data folder and organize various files to make it look more comfortable.
1. Set the runtime folder
index.php
define('RUNTIME_PATH', __DIR__ . '/data/runtime/');
2. Set upload to store uploaded images and upload files
3. Set static. Store jquery.js, bootstrap, some effect plug-ins and so on
// 视图输出字符串内容替换 'view_replace_str' => [ '__DATA__' => SITE_PATH.'data/', // 上传文件路径 '__UPLOAD__' =>SITE_PATH.'data/upload/', // 静态文件路径 (如bootshop,js,css) '__STATIC__' =>SITE_PATH.'data/upload/', ],
4. Define the template file path to facilitate calling css, js, images under the template
'view_replace_str' => [ // 模板文件路径 '__TEMPLATE__' => config('template.view_path').config('index.model_name').'/'.config('index.default_template') .'/', // 模板下的共享文件路径(css,js,images...) '__PUBLIC__' => SITE_PATH.'/'.config('template.view_path').config('index.model_name').'/'.config('index. default_template').'/public/', ],
Template page reference:
<script src=__PUBLIC__js/jqueyr.js”> <link href=”__PUBLIC__css/style.css”> <img src="__PUBLIC__images/1.png">
5. You can put whatever you want, set it yourself
6. Use of the common module common
The common module belongs to the public module, Thinkphp framework, and the default is Can be called.
Actual use: Extract the models, controls, and events that may be used by any module and put them under the public module.
1. Public event apps\common\common.php
Function: generally store password encryption, drop-down box encapsulation, read files under a certain folder
/** * 密码加密 * @param string $password * @param string $password_salt * @return string */ function password($password, $password_salt){ return md5(md5($password) . md5($password_salt)); }
2, Public configuration apps\common\config.php
Extract the common parts of the Index module and Admin module and put them here, such as: public template path
'template' => [ // 模板路径 'view_path' => 'template/', ]
3, public language package apps \common\lang\zh-cn.php
比如经常用到的词 提交成功、提交失败、执行成功、执行错误、添加成功、添加失败、修改成功、修改失败、删除成功、删除失败... 可以放到公共语言包,在Index模块、Admin模块都可以用的到。
<?php /** * 全局语言包 * zh-cn * */ return [ 'success' => '执行成功', 'error' => '执行失败', 'add_success' => '添加成功', 'add_error' => '添加失败', 'edit_success' => '修改成功', 'edit_error' => '修改失败', 'delete_success' => '删除成功', 'delete_error' => '删除失败', ];
php页面调用:$lang = lang('success')
html页面调用:{:lang('success')}
4、公共控制器 apps\common\common.php
跟上面差不多个意思 Index模块、Admin模块都能用到的放这里。
5、公共模块 apps\common\common.php
跟上面差不多个意思 Index模块、Admin模块都能用到的放这里。
七、设置错误页面①
设置网站的错误提示页面,也是一个很重要的环节。
1、空操作
在当前控制器里面增加_empty操作
public function _empty(){ $this->error('方法不存在'); } Public function index(){ }
测试方法:
正常:
http://localhost/thinkphp/index/index/index
错误: 会提示“方法不存在”
http://localhost/thinkphp/index/index/df
2、空控制器
在模块下建立Error控制器,
位置: index/error.php 相关参数:empty_controller
代码:
<?php /** * 前端首页 * */ namespace app\index\controller; use app\index\controller; class Error extends IndexBase { public function index(){ echo '访问的控制器不存在'; } }
测试:http://localhost/thinkphp/index/inde3dfx/index
3、异常错误抛出
能够影响它的是,当前模块下的配置文件。如果当前配置文件无效,则会自动锁定公共模块下的配置参数。
相关参数:exception_tmpl,error_message
// 异常页面的模板文件 'exception_tmpl'=> THINK_PATH . 'tpl' . DS . 'think_exception.tpl',
八、设置错误页面②
完美的去设置错误页面
1、准备一个错误页面 error.html,位置:thinkphp\template\index\default\error.html ,准备把前段所有的错误提示都指向这里。
2、空操作指向
在apps\index\controller\Indexbase.php,“基类”里面设置_empty。
<?php /** * 前端基类 * */ namespace app\index\controller; use app\Common\controller\Base; class IndexBase extends Base { public function _initialize() { parent::_initialize(); } /** * 空操作 跳转 * */ public function _empty(){ //abort(); exception(); // 这两种方法都可以 } }
3、空控制器指向
在apps\index\controller\Error.php
<?php /** * 空控制器跳转 * */ namespace app\index\controller; use app\index\controller; class Error extends IndexBase { public function index(){ abort(); } }
4、异常错误指向
在 index/config.php exception_tmpl 参数
'exception_tmpl' => THINK_PATH . 'tpl' . DS . 'think_exception.tpl', //'exception_tmpl' =>'E:/wamp/www/thinkphp/template/index/default/error.html',
注意:地址一定要绝对路径。
拓展,
401,404,500等错误页面自定义
相关参数:http_exception_template
手册地址:http://www.kancloud.cn/manual/thinkphp5/163256
代码:
config.php
'http_exception_template' => [ // 定义404错误的重定向页面地址 404 => ROOT_PATH.config('template.view_path').config('index.model_name').'/'.config ('index.default_template').'/404.html', // 还可以定义其它的HTTP status 401 => ROOT_PATH.config('template.view_path').config('index.model_name').'/'.config ('index.default_template').'/401.html', ],
控制器调用
abort(404,'错误信息')
error.html,404.html 页面代码,可以参考thinkphp\thinkphp\tpl\think_exception.tpl
九、路由别名Route
主要作用:隐藏自己的真实路由名称
Route.php
方法一:
<?php use think\Route; Route::alias('home','index/index'); Route::alias('admin','admin/index');
方法二:
<?php return [ '__pattern__' => [ 'name' => '\w+', ], '[hello]' => [ ':id' => ['index/hello', ['method' => 'get'], ['id' => '\d+']], ':name' => ['index/hello', ['method' => 'post']], ], '__alias__' => [ 'home' => 'index/index', 'admin'=> 'admin/index' ], ];
http://localhost/thinkphp/index.php/home/test 同等与http://localhost/thinkphp/index.php/index/index/test
http://localhost/thinkphp/index.php/admin/edit/ 同等与http://localhost/thinkphp/index.php/admin/index/edit
注释:别名 => ‘模型/控制器’ ( 别名等于模块+控制器)
十、路由设置,隐藏indx.php
网站根目录下.htaccess
<IfModule mod_rewrite.c> Options +FollowSymlinks -Multiviews RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ index.php/$1 [QSA,PT,L] </IfModule>
The above is the detailed content of How to use thinkphp. For more information, please follow other related articles on the PHP Chinese website!

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

AI Hentai Generator
Generate AI Hentai for free.

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



The DirectX repair tool is a professional system tool. Its main function is to detect the DirectX status of the current system. If an abnormality is found, it can be repaired directly. There may be many users who don’t know how to use the DirectX repair tool. Let’s take a look at the detailed tutorial below. 1. Use repair tool software to perform repair detection. 2. If it prompts that there is an abnormal problem in the C++ component after the repair is completed, please click the Cancel button, and then click the Tools menu bar. 3. Click the Options button, select the extension, and click the Start Extension button. 4. After the expansion is completed, re-detect and repair it. 5. If the problem is still not solved after the repair tool operation is completed, you can try to uninstall and reinstall the program that reported the error.

To run the ThinkPHP project, you need to: install Composer; use Composer to create the project; enter the project directory and execute php bin/console serve; visit http://localhost:8000 to view the welcome page.

ThinkPHP has multiple versions designed for different PHP versions. Major versions include 3.2, 5.0, 5.1, and 6.0, while minor versions are used to fix bugs and provide new features. The latest stable version is ThinkPHP 6.0.16. When choosing a version, consider the PHP version, feature requirements, and community support. It is recommended to use the latest stable version for best performance and support.

Introduction to HTTP 525 status code: Understand its definition and usage HTTP (HypertextTransferProtocol) 525 status code means that an error occurred on the server during the SSL handshake, resulting in the inability to establish a secure connection. The server returns this status code when an error occurs during the Transport Layer Security (TLS) handshake. This status code falls into the server error category and usually indicates a server configuration or setup problem. When the client tries to connect to the server via HTTPS, the server has no

Steps to run ThinkPHP Framework locally: Download and unzip ThinkPHP Framework to a local directory. Create a virtual host (optional) pointing to the ThinkPHP root directory. Configure database connection parameters. Start the web server. Initialize the ThinkPHP application. Access the ThinkPHP application URL and run it.

Many friends still don’t know how to use Baidu Netdisk, so the editor will explain how to use Baidu Netdisk below. If you are in need, hurry up and take a look. I believe it will be helpful to everyone. Step 1: Log in directly after installing Baidu Netdisk (as shown in the picture); Step 2: Then select "My Sharing" and "Transfer List" according to the page prompts (as shown in the picture); Step 3: In "Friend Sharing", you can share pictures and files directly with friends (as shown in the picture); Step 4: Then select "Share" and then select computer files or network disk files (as shown in the picture); Fifth Step 1: Then you can find friends (as shown in the picture); Step 6: You can also find the functions you need in the "Function Treasure Box" (as shown in the picture). The above is the editor’s opinion

How to use the copy-paste shortcut keys Copy-paste is an operation we often encounter when using computers every day. In order to improve work efficiency, it is very important to master the copy and paste shortcut keys. This article will introduce some commonly used copy and paste shortcut keys to help readers perform copy and paste operations more conveniently. Copy shortcut key: Ctrl+CCtrl+C is the shortcut key for copying. By holding down the Ctrl key and then pressing the C key, you can copy the selected text, files, pictures, etc. to the clipboard. To use this shortcut key,

The KMS Activation Tool is a software tool used to activate Microsoft Windows and Office products. KMS is the abbreviation of KeyManagementService, which is key management service. The KMS activation tool simulates the functions of the KMS server so that the computer can connect to the virtual KMS server to activate Windows and Office products. The KMS activation tool is small in size and powerful in function. It can be permanently activated with one click. It can activate any version of the window system and any version of Office software without being connected to the Internet. It is currently the most successful and frequently updated Windows activation tool. Today I will introduce it Let me introduce to you the kms activation work
