Table of Contents
:) 
Home PHP Framework ThinkPHP Create TP5.1 project using ThinkPHP

Create TP5.1 project using ThinkPHP

Jul 15, 2020 pm 02:00 PM
php thinkphp thinkphp5 thinkphp5.1 tp tp5 tp5.1

在前面,我们安装了ThinkPHP之后,那么如何用ThinkPHP开发项目呢?

1、 打开application/index/controller/Index.php,我们可以看到有如下代码。

<?php
namespace app\index\controller;
class Index
{
    public function index()
    {
        return &#39;<style type="text/css">*{ padding: 0; margin: 0; } div{ padding: 4px 48px;} a{color:#2E5CD5;cursor: pointer;text-decoration: none} a:hover{text-decoration:underline; } body{ background: #fff; font-family: "Century Gothic","Microsoft yahei"; color: #333;font-size:18px;} h1{ font-size: 100px; font-weight: normal; margin-bottom: 12px; } p{ line-height: 1.6em; font-size: 42px }</style><div style="padding: 24px 48px;"> <h1 id="nbsp">:) </h1><p> ThinkPHP V5.1<br/><span style="font-size:30px">12载初心不改(2006-2018) - 你值得信赖的PHP框架</span></p></div><script type="text/javascript" src="https://tajs.qq.com/stats?sId=64890268" charset="UTF-8"></script><script type="text/javascript" src="https://e.topthink.com/Public/static/client.js"></script><think id="eab4b9f840753f8e7"></think>&#39;;
    }
    public function hello($name = &#39;ThinkPHP5&#39;)
    {
        return &#39;hello,&#39; . $name;
    }
}
Copy after login

在上述代码中,

(1)、namespace app\index\controller 是命名空间。PHP中命名空间使用关键字namespace定义,其基本语法格式是:

        namespace 空间名称;
Copy after login

其中空间名称遵循基本标识符命名规则,以数字、字母和下划线构成,且不能以数字开头)。关于更多的命名空间,大家可以自行上网搜索。

(2)、class Index 是一个类,类中有index()和hello()方法,比如index()方法中的return返回的就是我们项目首页的HTML内容。

(3)、访问index()方法,直接通过http://localhost:8010/tp5.1.36/public这个URL进行访问(localhost表示的是本地主机,8010是Apache服务器的端口号,tp5.1.36是项目名)。

(4)、如果要访问hello()方法,那么就需要通过http://localhost:8010/tp5.1.36/public/index.php/index/index/hello这个URL来访问,打开后,网页中显示“hello,ThinkPHP5”.

ThinkPHP5.1完全开放手册是这样描述的:http://serverName/index.php(或者其它应用入口文件)/模块/控制器/操作/[参数名/参数值...]

那么我们来看这个地址

http://localhost:8010/tp5.1.36/public/index.php/index/index/hello

其中:

index.php后面的第一个index表示的是模块;

index.php后面的第二个index表示的是控制器;

hello表示的是index模块下的index控制器下的hello()方法。

(5)、可以通过URL重写隐藏应用的入口文件index.php(也可以是其它的入口文件,但URL重写通常只能设置一个入口文件),下面是相关服务器的配置参考(以apache为例):

1) httpd.conf配置文件中加载了mod_rewrite.so模块

2) AllowOverride None 将None改为 All

3) 把下面的内容保存为.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

2、 打开MySQL服务器,创建数据库,将数据库名称命名为student。

3、 在该数据库下创建一张表,表名为:student。

Create TP5.1 project using ThinkPHP

4、 向student表中插入如下数据

Create TP5.1 project using ThinkPHP

上面性别的取值中,1表示的是男,2表示的是女。

5、 编辑config/database.php文件,参考如下代码修改数据库的配置。

    // 数据库类型
    &#39;type&#39;            => &#39;mysql&#39;,
    // 服务器地址
    &#39;hostname&#39;        => &#39;127.0.0.1&#39;,
    // 数据库名
    &#39;database&#39;        => &#39;student&#39;,
    // 用户名
    &#39;username&#39;        => &#39;root&#39;,
    // 密码
     &#39;password&#39;        => &#39;root&#39;,
Copy after login

请根据自己的实际情况进行修改,我这里的用户名和密码都是root。

6、 在Index控制器下添加student()方法,将student表查询出来,具体代码如下。

   public function index()
  {
     $data=\think\Db::name(‘select * from `student`’);
     $arr=[];
        foreach($data as $v){
             $arr[]=$v[‘name’];
        }
     return implode(‘,’,$arr);
    }
Copy after login

通过访问localhost:8010/tp5.1.36/public/index.php/index/index/student进行测试,可以看到浏览器中显示的数据为:李四,张三,王五。

7、 在实际开发中,我们会遇到各种错误,为了更好的调试错误,ThinkPHP提供了非常强大的错误报告和跟踪调试功能。打开config/app.php文件,找到如下两行代码,将值改为true。

    ‘app_debug’ =>’true’,//应用调试模式
    ‘app_trace’ =>’true’,//应用trace
Copy after login

8、 在实际开发中,需要编写大量的HTML网页,为了方便编写HTML网页,我们可以单独将HTML放置在一个模板文件中。为了实现这个效果,需要让控制器中的Index类继承\think\Controller类,代码如下所示。

    class Index extends \think\Controller
Copy after login

9、 继承\think\Controller类后,就可以使用这个类提供的assgin()和fetch()方法。

10、 接下来修改student()方法中的代码内容,调用assgin()方法为模板赋值,再调用fetch()方法喧嚷模板,具体代码如下。

    public function index()
    {
      $data=\think\Db: name(‘student`’)->filed(‘name’)->select();
            $this->assgin(‘data’,$data);
        return $this->fetch();
    }
Copy after login

通过访问localhost:8010/tp5.1.36/public/index.php/index/index/student进行测试,会出现报错,是因为我们还没有创建该模板,根据提示可以找到该路径位于application/index/view/Index/student.html。手动创建模板文件和其所在的目录,编写代码如下:

    <!DOCTYPE html>
    <html>
        <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>学生信息列表</title>
        </head>
        <body>
       { foreach($data as $v)}
          <div>{$v.name]}></div>
       {/foreach;}
        </body>
</html>
Copy after login

11、这样就可以在模板文件中输出所有学生的姓名。

TP5.1的第一个项目就这样完成了,在后续的文章中,我们再进行细讲涉及到的知识点。

The above is the detailed content of Create TP5.1 project using 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

How to solve the problem of cURL error 77 when connecting to Elasticsearch 8 using ThinkPHP6 and elasticsearch-php clients? How to solve the problem of cURL error 77 when connecting to Elasticsearch 8 using ThinkPHP6 and elasticsearch-php clients? Mar 31, 2025 pm 11:36 PM

Using the ThinkPHP6 framework combined with elasticsearch-php client to operate Elasticsearch...

Explain the match expression (PHP 8 ) and how it differs from switch. Explain the match expression (PHP 8 ) and how it differs from switch. Apr 06, 2025 am 12:03 AM

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

See all articles