Home > Backend Development > PHP Tutorial > How to create an object-oriented blog using PHP

How to create an object-oriented blog using PHP

WBOY
Release: 2023-08-30 19:22:01
Original
1385 people have browsed it

如何使用 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;
Copy after login

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

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

id字段定义为INT,设置为主键,并配置为自增,类似于blog_posts表中的id字段。 first_namelast_nameurlemail字段设置为VARCHAR,最大长度为255。

创建 tags

继续运行以下命令来创建 tags 表。

CREATE TABLE tags (
  id INT PRIMARY KEY AUTO_INCREMENT,
  name VARCHAR(255)
);
Copy after login

和之前一样,id字段定义为INT,设置为主键,并配置为自增。 name 字段定义为 VARCHAR,最大长度为 255。

创建 blog_post_tags

继续运行以下命令来创建 blog_post_tags 表。

CREATE TABLE blog_post_tags (
  blog_post_id INT,
  tag_id INT
);
Copy after login

两个字段都定义为 INT 类型。

这就是创建数据库和表的过程。从下一节开始,我们将开始使用 PHP 实现我们的博客网站。

对象如何在 PHP OOP 中工作

在本节中,我们将简要讨论 PHP 中的 OOP。

面向对象的编程(通常称为 OOP)是一种帮助您以易于长期扩展和维护的方式开发复杂应用程序的方法。在 OOP 的世界中,现实世界的实体(例如 PersonCarAnimal)被视为对象。在面向对象的编程中,您通过使用对象与应用程序交互。这与过程式编程形成鲜明对比,在过程式编程中,您主要与函数和全局变量交互。

在 OOP 中,有的概念,它用于将现实世界的实体建模或映射到数据(属性)和功能(< em>方法)。 对象是类的实例,您可以创建同一类的多个实例。例如,有一个 Person 类,但许多 person 对象可以是该类的实例 — dan, zainab, hector

该类定义属性。例如,对于 Person 类,我们可能有 nameagephoneNumber。然后,每个 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;
    }
}
?>
Copy after login

在本课程中,我们将使用 mysqli 扩展来连接 MySQL 数据库,稍后我们将看到该扩展。构造函数需要一个 mysqli 连接对象。 __construct 方法称为构造函数,每当我们创建 BlogPost 对象的新实例时,都会自动调用它。接下来,我们为不同的目的定义了一些方法。

getBlogPosts 方法从 blog_posts 表中检索所有博客文章,加入 people 表以检索作者信息。

getTagsForBlogPost 方法检索与特定博客文章关联的标签,使用准备好的语句和参数绑定来防止 SQL 注入。

最后,getBlogPostById 方法允许您通过 ID 检索特定博客文章。它使用附加的 WHERE 子句扩展了现有的 blog_postspeople 表连接查询,以根据提供的 $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);
}
Copy after login

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

首先,我们使用 require 语句添加两个必需的文件,connection.phpblogpost.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!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template