首先,我們需要?jiǎng)?chuàng)建一個(gè)數(shù)據(jù)庫來存儲(chǔ)我們的商品和訂單信息。復(fù)制并粘貼以下sql代碼到phpMyAdmin或其他mysql客戶端中,即可創(chuàng)建數(shù)據(jù)庫:
CREATE database cart default CHARACTER SET utf8 COLLATE utf8_general_ci;
然后,我們需要?jiǎng)?chuàng)建兩個(gè)表來存儲(chǔ)商品和訂單信息。下述SQL語句是創(chuàng)建“products”和“orders”兩個(gè)表的: CREATE table products ( product_id int PRIMARY KEY, product_name VARCHAR(50), price DECIMAL(10,2) ); CREATE TABLE orders ( order_id INT PRIMARY KEY, product_id INT, order_date DATE, amount INT, FOREIGN KEY (product_id) REFERENCES products(product_id) );
CREATE?TABLE?products?( ?id?int(11)?NOT?NULL?AUTO_INCREMENT, ?name?varchar(255)?NOT?NULL, ?description?text?NOT?NULL, ?price?float?NOT?NULL, ?PRIMARY?KEY?(id) )?ENGINE=InnoDB?DEFAULT?CHARSET=utf8;
CREATE?TABLE?orders?( ?id?int(11)?NOT?NULL?AUTO_INCREMENT, ?user_id?int(11)?NOT?NULL, ?product_id?int(11)?NOT?NULL, ?quantity?int(11)?NOT?NULL, ?created_at?timestamp?NOT?NULL?DEFAULT?CURRENT_TIMESTAMP, ?PRIMARY?KEY?(id) )?ENGINE=InnoDB?DEFAULT?CHARSET=utf8;
現(xiàn)在,我們需要設(shè)置我們的應(yīng)用程序。使用composer安裝thinkphp框架:
composer create-project topthink/think tp5 ?–prefer-dist
立即學(xué)習(xí)“PHP免費(fèi)學(xué)習(xí)筆記(深入)”;
接著,把下面的代碼復(fù)制并粘貼到tp5/application/common.php文件里。全局幫助函數(shù)“getCart”將被創(chuàng)建,以獲取用戶購物車信息
<?php use appindexmodelCart; function getCart() { $user_id = 1; // 此處默認(rèn)用戶ID為1,實(shí)際應(yīng)用中應(yīng)該從會(huì)話中獲取用戶ID $cart = Cart::where('user_id', $user_id)->select(); return?$cart; }
接下來,我們需要?jiǎng)?chuàng)建一個(gè)名為“Cart”的模型來管理用戶購物車中的項(xiàng)目。
<?php namespace appindexmodel; use thinkModel; class Cart extends Model { protected $table = 'orders'; static function add($product_id, $quantity) { $user_id = 1; // 此處默認(rèn)用戶ID為1,實(shí)際應(yīng)用中應(yīng)該從會(huì)話中獲取用戶ID $order = new Cart(); $order->user_id?=?$user_id; ????$order->product_id?=?$product_id; ????$order->quantity?=?$quantity; ????$order->save(); } static?function?remove($id) { ????Cart::destroy($id); } }
我們現(xiàn)在能夠通過使用“Cart”模型在應(yīng)用程序中添加或刪除購物車中的商品。使用以下代碼將商品添加到購物車:
Cart::add($product_id,?$quantity);
而將商品從購物車中刪除的代碼如下:
Cart::remove($id);
最后,我們需要?jiǎng)?chuàng)建一個(gè)名為“Cart”的控制器,并添加兩個(gè)方法:一個(gè)用于顯示購物車內(nèi)容,另一個(gè)用于將商品添加到購物車。
<?php namespace appindexcontroller; use appindexmodelCart; class CartController extends BaseController { public function index() { $cart = getCart(); $this->assign('cart',?$cart); ????return?$this->fetch(); } public?function?add() { ????$product_id?=?input('post.product_id'); ????$quantity?=?input('post.quantity'); ????Cart::add($product_id,?$quantity); ????$this->success('添加成功',?url('index')); } }
完成上述步驟后,我們已經(jīng)成功創(chuàng)建了一個(gè)簡單的購物車應(yīng)用程序。現(xiàn)在,我們可以通過訪問CartController的index方法來顯示購物車內(nèi)容,并通過訪問CartController的add方法來將商品添加到購物車中。