How to create an object-oriented blog using PHP
In this article, we will further expand our knowledge of PHP and MySQL by creating a simple blog. While there are countless excellent free blogging platforms on the market, the purpose of this tutorial is to explore the process of creating a blogging website to learn advanced database structure techniques and how to use data more efficiently using object-oriented programming in PHP.
For this tutorial, I assume you have some basic understanding of PHP, MySQL, and XHTML.
Browse database structure
Before we jump into the MySQL client and start creating tables, we should outline what we want in the blog. The obvious things we need to include are blog posts, each post should include a title, the post itself, the author, and the date it was published.
Now, we just need to create a table to hold this information and most likely successfully create a basic blog. However, if there is only one table, we don't have as much control over the data. For example, we could store the author's name in the same table as the blog post, but what if we also want to store the author's email? Adding another field to our table would be the obvious solution.
The problem arises when you later want to change the author's email address. Now, you have to change it for every blog post that person creates.
So what we want to do is create a separate table called people
where we can store all the information about the author, such as email, URL, name, and unique ID. Then, in our blog_posts
table, we will reference that person by their unique ID. This ID is called a foreign key, and the relationship between the people
table and the blog_posts
table is called a one-to-many relationship because the same person can create multiple blog posts.
In addition to this, we would also like to provide the ability to attach tags to each blog post. A blog post can have multiple tags attached to it, so this is a one-to-many relationship. To do this, we need to create another table, which can be named something like blog_post_tags
. The table will contain two foreign keys: one for the ID of the blog post and one for the ID of the tag associated with the blog post. This way we can assign any number of tags to a blog post and still be able to edit information about that specific tag across all posts using a simple MySQL query. Of course, we also need the tags
table, which holds the actual tags, and which has two fields: id and name.
Now that we have an overview of what the database structure should look like, let's go ahead and create it. I will use PhpMyAdmin because it is the most widely used MySQL administration client and is easy to use. There are several different naming conventions you can use when creating database, table, and field names. I like to use all lowercase letters and underscores instead of spaces. You should avoid using uppercase characters as this is considered one of the best practices.
If you do not have PHP and MySQL on your system or a server that can run them, I recommend downloading standalone installations of Apache, PHP, and MySQL. MAMP is for Mac and WAMP is for PC.
Create database and tables
In this section, we will continue to create the database and necessary tables for our blog site.
Let's go ahead and create a new database called code_tutsplus_blog
. You can create a new database using the following MySQL commands in PhpMyAdmin or the MySQL CLI:
CREATE DATABASE code_tutsplus_blog;
After creating the database, we can continue to create the necessary tables.
Create blog_posts
table
Continue running the following commands to create the blog_posts
table.
CREATE TABLE blog_posts ( id INT PRIMARY KEY AUTO_INCREMENT, title VARCHAR(255), post TEXT, author_id INT, date_posted DATE );
blog_posts
table has five fields: id
, title
, post
, author_id
and date_posted
.
We created the id
field as the primary key and set it to auto-increment. It will generate a unique identifier for each entry. Whenever we add a new post, it is assigned a sequence number, starting at 1 and incrementing with each subsequent post.
Next, we also need to define the data type of each field. The id
field is set to type INT
(short for integer) since it should only store numeric values, and we set the maximum length to 11. title
The field is defined as VARCHAR
type, with a maximum length of 255. post
fields are defined as TEXT
type. The author_id
field has the same data type as the id
field. Finally, the date_posted
field is defined as a DATE
type.
创建 people
表
让我们继续创建下一个表,名为 people
。我们不称其为作者,因为将来我们可能希望创建注册和发表评论的功能,而这些人不会被视为作者。
继续运行以下命令来创建 people
表。
CREATE TABLE people ( id INT PRIMARY KEY AUTO_INCREMENT, first_name VARCHAR(255), last_name VARCHAR(255), url VARCHAR(255), email VARCHAR(255) );
id
字段定义为INT
,设置为主键,并配置为自增,类似于blog_posts
表中的id
字段。 first_name
、last_name
、url
、email
字段设置为VARCHAR
,最大长度为255。
创建 tags
表
继续运行以下命令来创建 tags
表。
CREATE TABLE tags ( id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(255) );
和之前一样,id
字段定义为INT
,设置为主键,并配置为自增。 name
字段定义为 VARCHAR
,最大长度为 255。
创建 blog_post_tags
表
继续运行以下命令来创建 blog_post_tags
表。
CREATE TABLE blog_post_tags ( blog_post_id INT, tag_id INT );
两个字段都定义为 INT
类型。
这就是创建数据库和表的过程。从下一节开始,我们将开始使用 PHP 实现我们的博客网站。
对象如何在 PHP OOP 中工作
在本节中,我们将简要讨论 PHP 中的 OOP。
面向对象的编程(通常称为 OOP)是一种帮助您以易于长期扩展和维护的方式开发复杂应用程序的方法。在 OOP 的世界中,现实世界的实体(例如 Person
、Car
或 Animal
)被视为对象。在面向对象的编程中,您通过使用对象与应用程序交互。这与过程式编程形成鲜明对比,在过程式编程中,您主要与函数和全局变量交互。
在 OOP 中,有类的概念,它用于将现实世界的实体建模或映射到数据(属性)和功能(< em>方法)。 对象是类的实例,您可以创建同一类的多个实例。例如,有一个 Person
类,但许多 person 对象可以是该类的实例 — dan
, zainab
, hector
等
该类定义属性。例如,对于 Person
类,我们可能有 name
、age
和 phoneNumber
。然后,每个 person 对象都会有自己的这些属性值。
您还可以在类中定义方法,以允许您操纵对象属性的值并对对象执行操作。例如,您可以定义 save
方法,将对象信息保存到数据库中。
在深入研究 PHP 代码之前,我们需要建立文件和文件夹结构。在本教程中,我们将在根文件夹中创建一个 index.php 文件。此外,我们将创建一个 includes 文件夹来存储 CSS 样式表、JavaScript 文件、connection.php 文件和 blogpost.php 文件。
创建 BlogPost
类
在本节中,我们将创建 BlogPost
类,它是我们博客应用程序的支柱。
继续并在 includes 文件夹中创建包含以下内容的 blogpost.php 文件。
<?php class BlogPost { private $conn; public function __construct($conn) { $this->conn = $conn; } public function getBlogPosts() { $query = "SELECT blog_posts.id, blog_posts.title, blog_posts.post, people.first_name, people.last_name, blog_posts.date_posted FROM blog_posts INNER JOIN people ON blog_posts.author_id = people.id"; $result = $this->conn->query($query); $blogPosts = $result->fetch_all(MYSQLI_ASSOC); return $blogPosts; } public function getTagsForBlogPost($blogPostId) { $query = "SELECT tags.name FROM tags INNER JOIN blog_post_tags ON tags.id = blog_post_tags.tag_id WHERE blog_post_tags.blog_post_id = ?"; $stmt = $this->conn->prepare($query); $stmt->bind_param('i', $blogPostId); $stmt->execute(); $result = $stmt->get_result(); $tags = []; while ($row = $result->fetch_assoc()) { $tags[] = $row['name']; } return $tags; } public function getBlogPostById($blogPostId) { $query = "SELECT blog_posts.id, blog_posts.title, blog_posts.post, people.first_name, people.last_name, blog_posts.date_posted FROM blog_posts INNER JOIN people ON blog_posts.author_id = people.id WHERE blog_posts.id = ?"; $stmt = $this->conn->prepare($query); $stmt->bind_param('i', $blogPostId); $stmt->execute(); $result = $stmt->get_result(); $blogPost = $result->fetch_assoc(); return $blogPost; } } ?>
在本课程中,我们将使用 mysqli
扩展来连接 MySQL 数据库,稍后我们将看到该扩展。构造函数需要一个 mysqli
连接对象。 __construct
方法称为构造函数,每当我们创建 BlogPost
对象的新实例时,都会自动调用它。接下来,我们为不同的目的定义了一些方法。
getBlogPosts
方法从 blog_posts
表中检索所有博客文章,加入 people
表以检索作者信息。
getTagsForBlogPost
方法检索与特定博客文章关联的标签,使用准备好的语句和参数绑定来防止 SQL 注入。
最后,getBlogPostById
方法允许您通过 ID 检索特定博客文章。它使用附加的 WHERE
子句扩展了现有的 blog_posts
和 people
表连接查询,以根据提供的 $blogPostId
过滤结果。
因此,我们创建了 BlogPost
类,我们可以使用它从数据库中检索博客文章并显示它,这就是我们下一节的内容。
显示博客文章
设置数据库连接
继续并在 includes 文件夹中创建包含以下内容的 connection.php 文件。
<?php $servername = "localhost"; $username = "your_username"; $password = "your_password"; $database = "your_database"; $conn = new mysqli($servername, $username, $password, $database); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); }
将 localhost
、your_username
、your_password
和 your_database
替换为您的实际数据库凭据。它建立与 MySQL 服务器的连接并将其存储在 $conn
对象中。
创建 index.php
文件
继续创建包含以下内容的 index.php 文件。
<?php require "includes/connection.php"; require "includes/blogpost.php"; $objBlogPost = new BlogPost($conn); $arrPosts = $objBlogPost->getBlogPosts(); ?> <div id="main"> <h1>My Simple Blog</h1> <div id="blogPosts"> <?php if (count($arrPosts)) { foreach ($arrPosts as $post) { $tags = implode(",", $objBlogPost->getTagsForBlogPost($post['id'])); echo "<div class='post'>"; echo "<h1>" . $post['title'] . "</h1>"; echo "<p>" . $post['post'] . "</h1>"; echo "<span class='footer'>Posted By: " . $post['first_name'] . " Posted On: " . $post['date_posted'] . " Tags: " . $tags . "</span>"; echo "</div>"; } } ?> </div> </div>
首先,我们使用 require
语句添加两个必需的文件,connection.php 和 blogpost.php。
然后,我们通过传递 $conn
对象(数据库连接)作为参数来创建 BlogPost
类的实例。它允许我们使用 BlogPost
类中定义的方法与博客文章数据进行交互。
接下来,我们使用了 BlogPost
类的 getBlogPosts
方法,该方法从数据库中获取博客文章并将其作为关联数组返回。
最后,我们使用 foreach
构造迭代数组记录,并通过使用 XHTML 格式化记录来显示记录。
这就是如何在 BlogPost
类的帮助下构建列表页面。
The above is the detailed content of How to create an object-oriented blog using PHP. 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

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

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





Alipay PHP...

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,

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

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.

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...
