search
HomePHP FrameworkThinkPHPCreate TP5.1 project using ThinkPHP

Create TP5.1 project using ThinkPHP

Jul 15, 2020 pm 02:00 PM
phpthinkphpthinkphp5thinkphp5.1tptp5tp5.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;
    }
}

在上述代码中,

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

        namespace 空间名称;

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

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

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;,

    请根据自己的实际情况进行修改,我这里的用户名和密码都是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);
    }

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

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

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

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

    class Index extends \think\Controller

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

        通过访问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>

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
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
What Are the Key Features of ThinkPHP's Built-in Testing Framework?What Are the Key Features of ThinkPHP's Built-in Testing Framework?Mar 18, 2025 pm 05:01 PM

The article discusses ThinkPHP's built-in testing framework, highlighting its key features like unit and integration testing, and how it enhances application reliability through early bug detection and improved code quality.

How to Use ThinkPHP for Building Real-Time Stock Market Data Feeds?How to Use ThinkPHP for Building Real-Time Stock Market Data Feeds?Mar 18, 2025 pm 04:57 PM

Article discusses using ThinkPHP for real-time stock market data feeds, focusing on setup, data accuracy, optimization, and security measures.

What Are the Key Considerations for Using ThinkPHP in a Serverless Architecture?What Are the Key Considerations for Using ThinkPHP in a Serverless Architecture?Mar 18, 2025 pm 04:54 PM

The article discusses key considerations for using ThinkPHP in serverless architectures, focusing on performance optimization, stateless design, and security. It highlights benefits like cost efficiency and scalability, but also addresses challenges

How to Implement Service Discovery and Load Balancing in ThinkPHP Microservices?How to Implement Service Discovery and Load Balancing in ThinkPHP Microservices?Mar 18, 2025 pm 04:51 PM

The article discusses implementing service discovery and load balancing in ThinkPHP microservices, focusing on setup, best practices, integration methods, and recommended tools.[159 characters]

What Are the Advanced Features of ThinkPHP's Dependency Injection Container?What Are the Advanced Features of ThinkPHP's Dependency Injection Container?Mar 18, 2025 pm 04:50 PM

ThinkPHP's IoC container offers advanced features like lazy loading, contextual binding, and method injection for efficient dependency management in PHP apps.Character count: 159

How to Use ThinkPHP for Building Real-Time Collaboration Tools?How to Use ThinkPHP for Building Real-Time Collaboration Tools?Mar 18, 2025 pm 04:49 PM

The article discusses using ThinkPHP to build real-time collaboration tools, focusing on setup, WebSocket integration, and security best practices.

What Are the Key Benefits of Using ThinkPHP for Building SaaS Applications?What Are the Key Benefits of Using ThinkPHP for Building SaaS Applications?Mar 18, 2025 pm 04:46 PM

ThinkPHP benefits SaaS apps with its lightweight design, MVC architecture, and extensibility. It enhances scalability, speeds development, and improves security through various features.

How to Build a Distributed Task Queue System with ThinkPHP and RabbitMQ?How to Build a Distributed Task Queue System with ThinkPHP and RabbitMQ?Mar 18, 2025 pm 04:45 PM

The article outlines building a distributed task queue system using ThinkPHP and RabbitMQ, focusing on installation, configuration, task management, and scalability. Key issues include ensuring high availability, avoiding common pitfalls like imprope

See all articles

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 agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.