Darryldecode 购物车是一种在您的项目中实现购物车功能的双向方法。就我而言,我正在尝试为愿望清单使用持久存储,这样当用户登录时,他们仍然会看到他们的愿望清单项目。首先要做的是通过运行命令来创建迁移
php artisan make:migration create_wishlist_storage_table
这会在database/migration目录下创建迁移文件,打开文件,用这几行代码替换整个代码块。
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateWishlistStorageTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('wishlist_storage', function (Blueprint $table) {
$table->string('id')->index();
$table->longText('wishlist_data');
$table->timestamps();
$table->primary('id');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('wishlist_storage');
}
}
之后,运行php artisan migrate 命令。这将在您的数据库中创建一个wishlist_storage 表,其中包含列id、wishlist_data 和时间戳。接下来是通过运行命令php artisan make:model DatabaseStorageModel 创建一个雄辩的模型来处理我们的迁移。打开应用目录下的 DatabaseStorageModel.php 文件,将整个代码块替换为以下代码行。
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class DatabaseStorageModel extends Model
{
//
/**
* Override eloquent default table
* @var string
*/
protected $table = 'wishlist_storage';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'id', 'wishlist_data',
];
/**
* Mutator for wishlist_column
* @param $value
*/
public function setWishlistDataAttribute($value)
{
$this->attributes['wishlist_data'] = serialize($value);
}
/**
* Accessor for wishlist_column
* @param $value
* @return mixed
*/
public function getWishlistDataAttribute($value)
{
return unserialize($value);
}
}
接下来要做的是创建一个新类以注入到我们的购物车实例中。为此,使用您的应用命名空间创建一个名为 DatabaseStorage.php 的文件并粘贴这行代码。
<?php
namespace App;
use Darryldecode\Cart\CartCollection;
class DatabaseStorage {
public function has($key)
{
return DatabaseStorageModel::find($key);
}
public function get($key)
{
if($this->has($key))
{
return new CartCollection(DatabaseStorageModel::find($key)->wishlist_data);
}
else
{
return [];
}
}
public function put($key, $value)
{
if($row = DatabaseStorageModel::find($key))
{
// update
$row->wishlist_data = $value;
$row->save();
}
else
{
DatabaseStorageModel::create([
'id' => $key,
'wishlist_data' => $value
]);
}
}
}
这取决于您命名文件和类的方式,但我正在解释我是如何做到的。最后一步是让 DatabaseStorage 类成为我们购物车的默认存储。运行命令
php artisan vendor:publish --provider="Darryldecode\Cart\CartServiceProvider" --tag="config"
在config目录下发布库配置文件名为shopping_cart.php。打开shopping_cart.php文件并替换
'storage'=>null,
与
'storage' => \App\DatabaseStorage::class,
您现在可以按照正常程序在控制器中使用购物车。