Home >PHP Framework >YII >Create 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:
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!