Home PHP Framework ThinkPHP How to use thinkphp

How to use thinkphp

Aug 26, 2019 pm 03:15 PM
thinkphp Instructions

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(&#39;APP_PATH&#39;, __DIR__ . &#39;/apps/&#39;);
// 加载框架引导文件
require  &#39;./thinkphp/start.php&#39;;
Copy after login

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(&#39;APP_PATH&#39;, __DIR__ . &#39;/../application/&#39;);
// 加载框架引导文件
require __DIR__ . &#39;/../thinkphp/start.php&#39;;
Copy after login

Add these two sentences at the end

$build = include &#39;../build.php&#39;;
// 运行自动生成
\think\Build::run($build);
Copy after login

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 [
    // 生成应用公共文件
    &#39;__file__&#39; => [&#39;common.php&#39;, &#39;config.php&#39;, &#39;database.php&#39;],
 
    // 定义demo模块的自动生成 (按照实际定义的文件名生成)
    &#39;demo&#39;     => [
        &#39;__file__&#39;   => [&#39;common.php&#39;],
        &#39;__dir__&#39;    => [&#39;behavior&#39;, &#39;controller&#39;, &#39;model&#39;, &#39;view&#39;],
        &#39;controller&#39; => [&#39;Index&#39;, &#39;Test&#39;, &#39;UserType&#39;],
        &#39;model&#39;      => [&#39;User&#39;, &#39;UserType&#39;],
        &#39;view&#39;       => [&#39;index/index&#39;],
    ],
    // 其他更多的模块定义
];
Copy after login

Then we add the file name we need here. The demo given can be commented out directly, as follows:

<?php
return [
    // 生成应用公共文件
    &#39;__file__&#39; => [&#39;common.php&#39;, &#39;config.php&#39;, &#39;database.php&#39;],
    //公共模块目录
    &#39;common&#39; => [
        &#39;__file__&#39;   => [&#39;common.php&#39;],
        &#39;__dir__&#39;    => [&#39;controller&#39;, &#39;model&#39;,&#39;lang&#39;],
        &#39;controller&#39; => [&#39;Index&#39;],
        &#39;model&#39;      => [&#39;Base&#39;],
    ],
    // Index模块
    &#39;home&#39;     => [
        &#39;__file__&#39;   => [&#39;common.php&#39;],
        &#39;__dir__&#39;    => [&#39;behavior&#39;, &#39;controller&#39;, &#39;model&#39;, &#39;view&#39;,&#39;lang&#39;],
        &#39;controller&#39; => [&#39;Index&#39;],
        &#39;model&#39;      => [&#39;Test&#39;],
        &#39;view&#39;       => [&#39;index/index&#39;],
    ],
    // Admin 模块
    &#39;admin&#39;     => [
        &#39;__file__&#39;   => [&#39;common.php&#39;],
        &#39;__dir__&#39;    => [&#39;behavior&#39;, &#39;controller&#39;, &#39;model&#39;, &#39;view&#39;,&#39;lang&#39;],
        &#39;controller&#39; => [&#39;Index&#39;],
        &#39;model&#39;      => [&#39;Test&#39;],
        &#39;view&#39;       => [&#39;index/index&#39;],
    ], 
];
Copy after login

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 &#39;./build.php&#39;;
// 运行自动生成
\think\Build::run($build);
Copy after login

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 &#39;原始基类&#39;;
    }
    public function test1(){
        return &#39;test1&#39;;
    }
}
Copy after login

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()
    {        
    }
}
Copy after login

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

(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.

&#39;template&#39;               => [// 模板路径
        &#39;view_path&#39;    => &#39;template/&#39;,     // 就是这里
/**
     * 前台文件配置
     * Author: MR.zhou
     * */
    &#39;index&#39; => [
        // 模快名称
        &#39;model_name&#39; =>&#39;index&#39;,
        // 默认模板文件名称
        &#39;default_template&#39; => &#39;default&#39;,       // 这里可以切换模块下的默认模板名称
    ],
    /**
     * 后台文件配置
     * Author: MR.zhou
     * */
    &#39;admin&#39;=>[
        // 模快名称
        &#39;model_name&#39; =>&#39;admin&#39;,
        // 默认模板文件名称
        &#39;default_template&#39; =>&#39;default&#39;,        // 这里可以切换模块下的默认模板名称
],
Copy after login

2. Set template parameters

index/config.php

&#39;template&#39;=> [
    // 模板路径
    &#39;view_path&#39;=> config(&#39;template.view_path&#39;).config(&#39;index.model_name&#39;).&#39;/&#39;.config(&#39;index.default_template&#39;).&#39;/&#39;,
],
Copy after login

admin/config.php

<?php
//配置文件
return [
    // 模板配置
    &#39;template&#39;               => [
        // 模板路径
        &#39;view_path&#39;    => config(&#39;template.view_path&#39;).config(&#39;admin.model_name&#39;).&#39;/&#39;.config(&#39;index.
        default_template&#39;).&#39;/&#39;,
    ],
];
Copy after login

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(&#39;RUNTIME_PATH&#39;, __DIR__ . &#39;/data/runtime/&#39;);
Copy after login

2. Set upload to store uploaded images and upload files

3. Set static. Store jquery.js, bootstrap, some effect plug-ins and so on

// 视图输出字符串内容替换
&#39;view_replace_str&#39;       => [
    &#39;__DATA__&#39; => SITE_PATH.&#39;data/&#39;,
    // 上传文件路径
    &#39;__UPLOAD__&#39; =>SITE_PATH.&#39;data/upload/&#39;,
    //  静态文件路径 (如bootshop,js,css)
    &#39;__STATIC__&#39; =>SITE_PATH.&#39;data/upload/&#39;,    
],
Copy after login

4. Define the template file path to facilitate calling css, js, images under the template

&#39;view_replace_str&#39;       => [
    // 模板文件路径
    &#39;__TEMPLATE__&#39; => config(&#39;template.view_path&#39;).config(&#39;index.model_name&#39;).&#39;/&#39;.config(&#39;index.default_template&#39;)
    .&#39;/&#39;,
    // 模板下的共享文件路径(css,js,images...)
    &#39;__PUBLIC__&#39; => SITE_PATH.&#39;/&#39;.config(&#39;template.view_path&#39;).config(&#39;index.model_name&#39;).&#39;/&#39;.config(&#39;index.
    default_template&#39;).&#39;/public/&#39;,
],
Copy after login

Template page reference:

<script src=__PUBLIC__js/jqueyr.js”>
<link href=”__PUBLIC__css/style.css”>
<img src="__PUBLIC__images/1.png">
Copy after login

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));
}
Copy after login

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

&#39;template&#39;               => [
    // 模板路径
    &#39;view_path&#39;    => &#39;template/&#39;,
]
Copy after login

3, public language package apps \common\lang\zh-cn.php

比如经常用到的词 提交成功、提交失败、执行成功、执行错误、添加成功、添加失败、修改成功、修改失败、删除成功、删除失败... 可以放到公共语言包,在Index模块、Admin模块都可以用的到。

<?php
/**
 * 全局语言包
 * zh-cn
 * */
return [
    &#39;success&#39;          => &#39;执行成功&#39;,
    &#39;error&#39;            => &#39;执行失败&#39;,
    &#39;add_success&#39;      => &#39;添加成功&#39;,
    &#39;add_error&#39;        => &#39;添加失败&#39;,
    &#39;edit_success&#39;     => &#39;修改成功&#39;,
    &#39;edit_error&#39;       => &#39;修改失败&#39;,
    &#39;delete_success&#39;   => &#39;删除成功&#39;,
    &#39;delete_error&#39;     => &#39;删除失败&#39;,
];
Copy after login

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(&#39;方法不存在&#39;);
}
Public function index(){       
}
Copy after login

测试方法:

正常:

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 &#39;访问的控制器不存在&#39;;
    }
}
Copy after login

测试:http://localhost/thinkphp/index/inde3dfx/index

3、异常错误抛出

能够影响它的是,当前模块下的配置文件。如果当前配置文件无效,则会自动锁定公共模块下的配置参数。

相关参数:exception_tmpl,error_message

// 异常页面的模板文件
&#39;exception_tmpl&#39;=> THINK_PATH . &#39;tpl&#39; . DS . &#39;think_exception.tpl&#39;,
Copy after login

八、设置错误页面②

完美的去设置错误页面

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();     //  这两种方法都可以
    }
}
Copy after login

3、空控制器指向

在apps\index\controller\Error.php

<?php
/**
 * 空控制器跳转
 * */
namespace app\index\controller;
use app\index\controller;
class Error extends IndexBase
{
    public function index(){
        abort();
    }
}
Copy after login

4、异常错误指向

在 index/config.php exception_tmpl 参数

&#39;exception_tmpl&#39;         => THINK_PATH . &#39;tpl&#39; . DS . &#39;think_exception.tpl&#39;,
 //&#39;exception_tmpl&#39; =>&#39;E:/wamp/www/thinkphp/template/index/default/error.html&#39;,
Copy after login

注意:地址一定要绝对路径。

拓展,

401,404,500等错误页面自定义

相关参数:http_exception_template

手册地址:http://www.kancloud.cn/manual/thinkphp5/163256

代码:

config.php

&#39;http_exception_template&#39;    =>  [
        // 定义404错误的重定向页面地址
        404 =>  ROOT_PATH.config(&#39;template.view_path&#39;).config(&#39;index.model_name&#39;).&#39;/&#39;.config
        (&#39;index.default_template&#39;).&#39;/404.html&#39;,
        // 还可以定义其它的HTTP status
        401 =>  ROOT_PATH.config(&#39;template.view_path&#39;).config(&#39;index.model_name&#39;).&#39;/&#39;.config
        (&#39;index.default_template&#39;).&#39;/401.html&#39;,
    ],
Copy after login

控制器调用

abort(404,'错误信息')

error.html,404.html 页面代码,可以参考thinkphp\thinkphp\tpl\think_exception.tpl

九、路由别名Route

主要作用:隐藏自己的真实路由名称

Route.php

方法一:

<?php
use think\Route;
Route::alias(&#39;home&#39;,&#39;index/index&#39;);
Route::alias(&#39;admin&#39;,&#39;admin/index&#39;);
Copy after login

方法二:

<?php
return [
    &#39;__pattern__&#39; => [
        &#39;name&#39; => &#39;\w+&#39;,
    ],
    &#39;[hello]&#39;     => [
        &#39;:id&#39;   => [&#39;index/hello&#39;, [&#39;method&#39; => &#39;get&#39;], [&#39;id&#39; => &#39;\d+&#39;]],
        &#39;:name&#39; => [&#39;index/hello&#39;, [&#39;method&#39; => &#39;post&#39;]],
    ],
    &#39;__alias__&#39; =>  [
        &#39;home&#39;  =>  &#39;index/index&#39;,
       &#39;admin&#39;=> &#39;admin/index&#39;
    ],
];
Copy after login

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>
Copy after login

The above is the detailed content of How to use thinkphp. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use DirectX repair tool? Detailed usage of DirectX repair tool How to use DirectX repair tool? Detailed usage of DirectX repair tool Mar 15, 2024 am 08:31 AM

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.

How to run thinkphp project How to run thinkphp project Apr 09, 2024 pm 05:33 PM

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.

There are several versions of thinkphp There are several versions of thinkphp Apr 09, 2024 pm 06:09 PM

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: explore its definition and application Introduction to HTTP 525 status code: explore its definition and application Feb 18, 2024 pm 10:12 PM

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

How to run thinkphp How to run thinkphp Apr 09, 2024 pm 05:39 PM

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.

How to use Baidu Netdisk-How to use Baidu Netdisk How to use Baidu Netdisk-How to use Baidu Netdisk Mar 04, 2024 pm 09:28 PM

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

Learn to copy and paste quickly Learn to copy and paste quickly Feb 18, 2024 pm 03:25 PM

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,

What is the KMS activation tool? How to use the KMS activation tool? How to use KMS activation tool? What is the KMS activation tool? How to use the KMS activation tool? How to use KMS activation tool? Mar 18, 2024 am 11:07 AM

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

See all articles