search
HomePHP FrameworkYIICreate an online store using the Yii framework

As a web developer, learning and practicing using the PHP framework is undoubtedly essential. Among many PHP frameworks, the Yii framework is an efficient, elegant, and secure framework with a wide user base.

In this article, I will share how to use the Yii framework to create a basic online mall application. The application will have basic mall functions such as user management, product management and shopping cart functions. This application can be used as an introductory practice for beginners to learn the Yii framework.

Install the Yii framework

Before we start using the Yii framework, we need to install the framework first. The Yii framework provides multiple installation methods, the most commonly used method is to install using Composer. Before installation, we need to confirm that Composer is installed.

We can use the following command to install the Yii framework:

composer create-project --prefer-dist yiisoft/yii2-app-basic basic

The above command will create a basic application. You can confirm whether the Yii framework is installed successfully by visiting http://localhost/basic.

Data table design and data filling

Before creating an online mall application, we need to create a data table related to the mall and fill in the data. This article will use MySQL as the database and create the following data table:

  • User table: stores user information, such as user name, password, and email.
  • Product table: Stores product information, such as name, price and description.
  • Order table: stores order information, such as user ID, product ID and order quantity.
  • Cart table: Stores shopping cart information, such as user ID, product ID and quantity, etc.

Adding appropriate indexes to the above data tables can improve query efficiency.

The following is the SQL statement to create the above data table:

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `product` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `price` float(10,2) NOT NULL,
  `description` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `order` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `product_id` int(11) NOT NULL,
  `quantity` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `user_id` (`user_id`),
  KEY `product_id` (`product_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `cart` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `product_id` int(11) NOT NULL,
  `quantity` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `user_id` (`user_id`),
  KEY `product_id` (`product_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Now, we need to fill in the data to test the application. Add at least one user record to the user table and at least one product record to the product table. We will use this user and product as test data for the remainder of this article.

Creating a User Controller

We will start by creating a User Controller. In the Yii framework, controllers are the core components that handle application requests. The controller is responsible for detecting the request type and calling the response operation method based on the request.

Now, we create the UserController controller and add basic action methods. We will use the yiiwebController extension to create the controller.

In Yii, the controller class name is usually added with the Controller suffix, which can better describe the functions implemented by the class. The following is the basic code of the UserController class:

<?php

namespace appcontrollers;

use yiiwebController;

class UserController extends Controller
{
    public function actionIndex()
    {
        return $this->render('index');
    }

    public function actionLogin()
    {
        // code for login logic
    }

    public function actionRegister()
    {
        // code for registration logic
    }
}

In the above code, we have added three basic operation methods. The actionIndex() method will render the index.php view file. This is the default action method name. The actionLogin() and actionRegister() methods will be used for user login and registration.

Now, we need to create the index.php view file. View files are the output of action methods in the controller. We will use the Yii::$app->view->render() method provided by the Yii framework to render the view.

Create the index.php file in the views/user folder and add the following code:

<?php

use yiihelpersHtml;

$this->title = 'User';
$this->params['breadcrumbs'][] = $this->title;
?>
<h1><?= Html::encode($this->title) ?></h1>
<p>
Welcome to the user homepage.
</p>

The above code will display a simple welcome message on the browser.

Creating the product controller and view

Now, we will move on to creating the product controller and view. We will use yiidataActiveDataProvider extension to get the product list data.

Create a ProductController controller and add the following action method:

<?php

namespace appcontrollers;

use yiiwebController;
use appmodelsProduct;
use yiidataActiveDataProvider;

class ProductController extends Controller
{
    public function actionIndex()
    {
        $dataProvider = new ActiveDataProvider([
            'query' => Product::find(),
        ]);

        return $this->render('index', [
            'dataProvider' => $dataProvider,
        ]);
    }

    public function actionAddtocart($id)
    {
        // code for add to cart logic
    }
}

As shown in the code, we first use Product::find() to get all products. We then put the product list data in an ActiveDataProvider and pass it to the view. After this, we create the actionAddtocart() method for adding items to the shopping cart.

We need to create the product folder and create the index.php view file under this folder. We use a GridView widget that will render a list of products based on the data provided by the dataProvider. We also add a button for adding products to the cart.

The following is the code of the views/product/index.php file:

<?php

use yiihelpersHtml;
use yiigridGridView;

$this->title = 'Product';
$this->params['breadcrumbs'][] = $this->title;
?>
<h1><?= Html::encode($this->title) ?></h1>

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
        'id',
        'name',
        'price',
        'description',
        [
            'class' => 'yiigridActionColumn',
            'buttons' => [
                'addtocart' => function ($url, $model) {
                    return Html::a('Add to cart', ['product/addtocart', 'id' => $model->id]);
                }
            ],
            'template' => '{addtocart}',
        ],
    ],
]); ?>

Now, we can confirm the view by visiting http://localhost/basic/product/index in the browser is rendered correctly.

Create a shopping cart controller and view

We need a shopping cart controller and view to manage the items added to the shopping cart in the mall. We will use session to store shopping cart data.

We create the CartController controller and add the following operation method:

<?php

namespace appcontrollers;

use yiiwebController;
use Yii;

class CartController extends Controller
{
    public function actionIndex()
    {
        $cart = Yii::$app->session->get('cart');
        return $this->render('index', [
            'cart' => $cart,
        ]);
    }

    public function actionAdd($id)
    {
        // code for add product to cart logic
    }

    public function actionRemove($id)
    {
        // code for remove product from cart logic
    }
}

In the above code, we first obtain the shopping cart data stored in the session. In the actionAdd($id) method, we will add the product with the specified ID number to the shopping cart. In the actionRemove($id) method, we will remove the item with the specified ID number from the shopping cart.

Next, we need to create the cart folder and create the index.php view file under this folder. We use the ListView widget which will render the shopping cart list based on the shopping cart data stored in the session. We also added some buttons for increasing or decreasing the number of items in the cart or removing items from the cart.

The following is the code of views/cart/index.php file:

<?php

use yiihelpersHtml;
use yiiwidgetsListView;

$this->title = 'Shopping Cart';
$this->params['breadcrumbs'][] = $this->title;
?>
<h1><?= Html::encode($this->title) ?></h1>

<?= ListView::widget([
    'dataProvider' => $dataProvider,
    'itemView' => '_cart_item',
    'emptyText' => 'Your cart is empty.',
]) ?>

在views/cart文件夹下创建_cart_item.php视图文件,该文件将被用于渲染购物车列表中的每一行。以下是views/cart/_cart_item.php文件的代码:

<?php

use yiihelpersHtml;
use yiiwidgetsActiveForm;

$form = ActiveForm::begin([
    'id' => 'cart-item-' . $model['id'],
]); ?>

<?= Html::a('Remove', ['cart/remove', 'id' => $model['id']]) ?>

<?= $model['name'] ?>

<?= $form->field($model, 'quantity')->textInput(['value' => $model['quantity']]) ?>

<?= Html::submitButton('Update') ?>

<?php ActiveForm::end(); ?>

以上代码将会在浏览器中显示购物车列表,用户可以在该列表中执行增加或减少商品数量的操作,也可以删除购物车中已有商品。

完成在线商城应用程序

现在,我们已经完成了基础的在线商城应用程序,该应用程序拥有用户管理,产品管理和购物车等基础功能。该应用程序可以作为初学者学习和实践Yii框架的入门实践。当然,在实际应用中,我们仍需要添加更多功能来满足商城的需求。

The above is the detailed content of Create an online store using the Yii framework. 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
Yii's Purpose: Building Web Applications Quickly and EfficientlyYii's Purpose: Building Web Applications Quickly and EfficientlyApr 22, 2025 am 12:07 AM

Yii's purpose is to enable developers to quickly and efficiently build web applications. Its implementation is implemented through the following methods: 1) Component-based design and MVC architecture to improve code maintainability and reusability; 2) Gii tools automatically generate code to improve development speed; 3) Lazy loading and caching mechanism optimization performance; 4) Flexible scalability to facilitate integration of third-party libraries; 5) Provide RBAC functions to handle complex business logic.

Yii's Versatility: From Simple Sites to Complex ProjectsYii's Versatility: From Simple Sites to Complex ProjectsApr 21, 2025 am 12:08 AM

Yiiisversatileavssuitable Projectsofallsizes.1) Simple Sites, YiiOofferseassetupandrapiddevelopment.2) ForcomplexProjects, ITModularityandrbacSystemManagescalabilityandSecurity effective.

Yii and the Future of PHP FrameworksYii and the Future of PHP FrameworksApr 20, 2025 am 12:11 AM

The Yii framework will continue to play an important role in the future development of PHP frameworks. 1) Yii provides efficient MVC architecture, powerful ORM system, built-in caching mechanism and rich extension libraries. 2) Its componentized design and flexibility make it suitable for complex business logic and RESTful API development. 3) Yii is constantly updated to adapt to modern PHP features and technical trends, such as microservices and containerization.

Yii in Action: Real-World Examples and ApplicationsYii in Action: Real-World Examples and ApplicationsApr 19, 2025 am 12:03 AM

The Yii framework is suitable for developing web applications of all sizes, and its advantages lie in its high performance and rich feature set. 1) Yii adopts an MVC architecture, and its core components include ActiveRecord, Widget and Gii tools. 2) Through the request processing process, Yii efficiently handles HTTP requests. 3) Basic usage shows a simple example of creating controllers and views. 4) Advanced usage demonstrates the flexibility of database operations through ActiveRecord. 5) Debugging skills include using the debug toolbar and logging system. 6) Performance optimization It is recommended to use cache and database query optimization, follow coding specifications and dependency injection to improve code quality.

How to display error prompts in yii2How to display error prompts in yii2Apr 18, 2025 pm 11:09 PM

In Yii2, there are two main ways to display error prompts. One is to use Yii::$app-&gt;errorHandler-&gt;exception() to automatically catch and display errors when an exception occurs. The other is to use $this-&gt;addError(), which displays an error when model validation fails and can be accessed in the view through $model-&gt;getErrors(). In the view, you can use if ($errors = $model-&gt;getErrors())

What are the differences between yi2 and tp5What are the differences between yi2 and tp5Apr 18, 2025 pm 11:06 PM

With the continuous development of PHP framework technology, Yi2 and TP5 have attracted much attention as the two mainstream frameworks. They are all known for their outstanding performance, rich functionality and robustness, but they have some differences and advantages and disadvantages. Understanding these differences is crucial for developers to choose frameworks.

What software is better for yi framework? Recommended software for yi frameworkWhat software is better for yi framework? Recommended software for yi frameworkApr 18, 2025 pm 11:03 PM

Abstract of the first paragraph of the article: When choosing software to develop Yi framework applications, multiple factors need to be considered. While native mobile application development tools such as XCode and Android Studio can provide strong control and flexibility, cross-platform frameworks such as React Native and Flutter are becoming increasingly popular with the benefits of being able to deploy to multiple platforms at once. For developers new to mobile development, low-code or no-code platforms such as AppSheet and Glide can quickly and easily build applications. Additionally, cloud service providers such as AWS Amplify and Firebase provide comprehensive tools

How to limit the rate of Yi2How to limit the rate of Yi2Apr 18, 2025 pm 11:00 PM

The Yi2 Rate Limiting Guide provides users with a comprehensive guide to how to control the data transfer rate in Yi2 applications. By implementing rate limits, users can optimize application performance, prevent excessive bandwidth consumption and ensure stable and reliable connections. This guide will introduce step-by-step how to configure the rate limit settings of Yi2, covering a variety of platforms and scenarios to meet the different needs of users.

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

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor