Categories
php

laravel wechat

用户登录流程

小程序调用 wx.login 后获得 code ,调用 laravel-wechat 的login 接口

https://depscreen.studentvision.cn/api/wechat/mini/login

返回 用户个人信息 openid accessToken 等

{
	"error_code": 0,
	"data": {
		"access_token": "bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL2RlcHNjcmVlbi5zdHVkZW50dmlzaW9uLmNuL2FwaS93ZWNoYXQvbWluaS9sb2dpbiIsImlhdCI6MTczMzk4NzMzMCwiZXhwIjoxNzMzOTkwOTMwLCJuYmYiOjE3MzM5ODczMzAsImp0aSI6IkFUTTloR1dvU1VuNjlaWWgiLCJzdWIiOiIxIiwicHJ2IjoiNDI1MTRkODBlZTM4NWRhODRjYTM4YWY0NTgyZThmNTRiYjRjZmIzOSJ9.qLXirUDL8GJjkg3LS47_J1LEpdA5j02VgyfUrt6RrpY",
		"expires_in": 3600,
		"wechat_user": {
			"id": 1,
			"app_id": "wx621e0fe15a370854",
			"user_id": "0",
			"openid": "oLG3w68wIQoTn5BwLOVyREIMtiFM",
			"nickname": null,
			"avatar": null,
			"gender": "0",
			"country": null,
			"province": null,
			"city": null,
			"subscribed_at": null,
			"created_at": "2024-12-11T04:15:17.997000Z",
			"updated_at": "2024-12-11T04:15:17.997000Z",
			"gender_readable": null
		}
	}
}

之后的每个请求都要带上 该jwt access token 作为通信票据以保证安全

Accept:application/json
Content-Type:application/json
Authorization:bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL2RlcHNjcmVlbi5zdHVkZW50dmlzaW9uLmNuL2FwaS93ZWNoYXQvbWluaS9sb2dpbiIsImlhdCI6MTczMzk4NzMzMCwiZXhwIjoxNzMzOTkwOTMwLCJuYmYiOjE3MzM5ODczMzAsImp0aSI6IkFUTTloR1dvU1VuNjlaWWgiLCJzdWIiOiIxIiwicHJ2IjoiNDI1MTRkODBlZTM4NWRhODRjYTM4YWY0NTgyZThmNTRiYjRjZmIzOSJ9.qLXirUDL8GJjkg3LS47_J1LEpdA5j02VgyfUrt6RrpY

controller 增加一个middleware 作为checking

Route::middleware('auth:mini')

具体实现类是
这个作为jwt入口
 Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
 php artisan  jwt:secret

该命令可以重新生成jwt 私钥

Categories
nginx php

nginx 下 laravel 部署

server {
                listen       8080;
                server_name  laravel.localhost;

                client_max_body_size 10M;
                # Load configuration files for the default server block.

                

                location / {
                        root           D://robin-admin/public;
                        index  index.html index.htm index.php;
                        try_files $uri $uri/ /index.php?$query_string;
                }

                location ~ \.php$ {
                    root           D://robin-admin/public;
                    fastcgi_pass   127.0.0.1:9000;
                    fastcgi_index  index.php;
                    fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
                    include        fastcgi_params;
                }

                error_page 404 /404.html;
                        location = /40x.html {
                }

                error_page 500 502 503 504 /50x.html;
                        location = /50x.html {
                }
    }

nginx 根目录指向laravel 的下的public 文件夹

try_files $uri $uri/ /index.php?$query_string; 可以有效重新访问后缀(不需要显式指明php后缀)

Categories
php

php artisan tinker

今天,我们将通过介绍 Laravel 中一个不太为人所知的功能,来展示如何快捷的调试数据库中的数据。通过使用 Laravel artisan 内建的 php artisan tinker, 我们可以很方便的看到数据库中的数据并且执行各种想要的操作。

Laravel artisan 的 tinker 是一个 REPL (read-eval-print-loop),REPL 是指交互式命令行界面,它可以让你输入一段代码去执行,并把执行结果直接打印到命令行界面里。

// see the count of all users
App\User::count();

// find a specific user and see their attributes
App\User::where('username', 'samuel')->first();

// find the relationships of a user
$user = App\User::with('posts')->first();
$user->posts;
factory(App\User::class, 10)->create();
App\User::all();
App\User::count();
$user = new App\User;
$user->name = "Wruce Bayne";
$user->email = "iambatman@savegotham.com";
$user->save();
doc XXX

查阅某个方法的文档

show XXX

显示某个方法的代码

Categories
php

laravel Form magic 方法

laravel 的form 对象 有magic方法 可以快速添加表单项

/**
 * Class Form.
 *
 * @method Field\Text           text($name, $label = '')
 * @method Field\Password       password($name, $label = '')
 * @method Field\Checkbox       checkbox($name, $label = '')
 * @method Field\CheckboxButton checkboxButton($name, $label = '')
 * @method Field\CheckboxCard   checkboxCard($name, $label = '')
 * @method Field\Radio          radio($name, $label = '')
 * @method Field\RadioButton    radioButton($name, $label = '')
 * @method Field\RadioCard      radioCard($name, $label = '')
 * @method Field\Select         select($name, $label = '')
 * @method Field\MultipleSelect multipleSelect($name, $label = '')
 * @method Field\Textarea       textarea($name, $label = '')
 * @method Field\Hidden         hidden($name, $label = '')
 * @method Field\Id             id($name, $label = '')
 * @method Field\Ip             ip($name, $label = '')
 * @method Field\Url            url($name, $label = '')
 * @method Field\Color          color($name, $label = '')
 * @method Field\Email          email($name, $label = '')
 * @method Field\Mobile         mobile($name, $label = '')
 * @method Field\Slider         slider($name, $label = '')
 * @method Field\File           file($name, $label = '')
 * @method Field\Image          image($name, $label = '')
 * @method Field\Date           date($name, $label = '')
 * @method Field\Datetime       datetime($name, $label = '')
 * @method Field\Time           time($name, $label = '')
 * @method Field\Year           year($column, $label = '')
 * @method Field\Month          month($column, $label = '')
 * @method Field\DateRange      dateRange($start, $end, $label = '')
 * @method Field\DateTimeRange  dateTimeRange($start, $end, $label = '')
 * @method Field\TimeRange      timeRange($start, $end, $label = '')
 * @method Field\Number         number($name, $label = '')
 * @method Field\Currency       currency($name, $label = '')
 * @method Field\SwitchField    switch($name, $label = '')
 * @method Field\Display        display($name, $label = '')
 * @method Field\Rate           rate($name, $label = '')
 * @method Field\Divider        divider($title = '')
 * @method Field\Decimal        decimal($column, $label = '')
 * @method Field\Html           html($html)
 * @method Field\Tags           tags($column, $label = '')
 * @method Field\Icon           icon($column, $label = '')
 * @method Field\Captcha        captcha($column, $label = '')
 * @method Field\Listbox        listbox($column, $label = '')
 * @method Field\Table          table($column, $label, $builder)
 * @method Field\Timezone       timezone($column, $label = '')
 * @method Field\KeyValue       keyValue($column, $label = '')
 * @method Field\ListField      list($column, $label = '')
 * @method mixed                handle(Request $request)
 */

真实调用的方法

 /**
     * Generate a Field object and add to form builder if Field exists.
     *
     * @param string $method
     * @param array  $arguments
     *
     * @return Field|$this
     */
    public function __call($method, $arguments)
    {
        if (!$this->hasField($method)) {
            return $this;
        }

        $class = BaseForm::$availableFields[$method];

        $field = new $class(Arr::get($arguments, 0), array_slice($arguments, 1));

        return tap($field, function ($field) {
            $this->pushField($field);
        });
    }
Categories
php

DB Facade

使用laravel 的数据库Facade 可以比较好的 执行数据库sql

$array = DB::select("select * from admin_users");
//raw 执行sql      

$object = DB::table("admin_users")->where("id","=","1")->first();
//获取查询第一条

$array = DB::table("admin_users")->where("id","=","1")->get();
//
get获取数据列表
       
$array = DB::table("admin_users")->where("id","=","1")->skip(0)->take(1)->get();
//分页查询

$array = DB::table("admin_users")->where("id","=","1")->skip(0)->limit(1)->get();
//分页查询

DB::transaction(function (){
           //内部执行开启事务
});

//手动控制事务
DB::beginTransaction();
DB::commit();
DB::rollBack();
Categories
php

laravel 入口

php 通过 symfony/http-foundation(http请求响应封装) 框架捕获http请求

laravel kernel 类 为laravel http 入口

middleware 类似于 过滤器 可以执行请求处理 然后next 执行处理链 必定有 handle 方法 当需要处理请求前操作 在调用 $next 前修改请求信息 当需要处理请求后 或者 在响应上操作 则 在$next后 修改信息 且返回结果必定为 $response对象

public function handle($request, Closure $next)
    {
        // Check if we're dealing with CORS and if we should handle it
        if (! $this->shouldRun($request)) {
            return $next($request);
        }

        // For Preflight, return the Preflight response
        if ($this->cors->isPreflightRequest($request)) {
            $response = $this->cors->handlePreflightRequest($request);

            $this->cors->varyHeader($response, 'Access-Control-Request-Method');

            return $response;
        }

        // Add the headers on the Request Handled event as fallback in case of exceptions
        if (class_exists(RequestHandled::class) && $this->container->bound('events')) {
            $this->container->make('events')->listen(RequestHandled::class, function (RequestHandled $event) {
                $this->addHeaders($event->request, $event->response);
            });
        }

        // Handle the request
        $response = $next($request);

        if ($request->getMethod() === 'OPTIONS') {
            $this->cors->varyHeader($response, 'Access-Control-Request-Method');
        }

        return $this->addHeaders($request, $response);
    }
Categories
php

laravel-admin form

  protected function form()
    {

        $form = new Form(new InfusionTicket());

        $form->select('clinic_id', "诊所信息")->options(Clinic::all()->pluck('name', 'id'))->required();
        $form->date('date', __('Date'))->default(date('Y-m-d'))->required();
        $form->select('inject', __('Inject'))->options(['静脉输液'=>'静脉输液',"肌肉(皮下)注射"=>"肌肉(皮下)注射","抽血"=>"抽血"])->required();
        $form->number('ticket', __('Ticket'))->required();
        $form->select('time_index', __('时间'))->options(InfusionTicketController::$timeArray)->required();
        $form->hidden('time');

        $form->saving(function ($form){

            $timeIndex = $form->time_index;
            Log::debug('数据');
            Log::debug($timeIndex);
            $time = InfusionTicketController::$timeArray[$timeIndex];
            Log::debug($time);
            $form->time= $time;
        });
        //保存后回调
        $form->saved(function ($form){
            Log::debug("执行创建");
            $model = $form->model();
            $clinicId = $model->clinic_id;
            $inject = $model->inject=='静脉输液'?'jmsy':'default';
            $date = $model->date;
            $dateFormat = Carbon::parse($date)->format('Y-m-d');
            $timeIndex = $model->time_index;
            $ticket = $model->ticket;
            Redis::select(2);
            $key = 'infusion-tickets:'.$clinicId.':'.$inject.':'.$dateFormat.':'.$timeIndex;
            Log::info($key);
            Redis::set($key,$ticket);

        });

        return $form;
  

在form表单中设置time为不可见(一定要设置time 不然无法保存time信息)

上述代码在保存时 添加time信息

在保存后 把对应信息 存储在redis中

 protected function detail($id)
    {
        $show = new Show(InfusionTicket::findOrFail($id));
        $show->panel()->tools(function ( \Encore\Admin\Show\Tools $tools) {
            $tools->disableEdit();
        });

        $show->clinic('诊所信息', function ($clinic)  {
            $clinic->setResource('/admin/clinics/');
            $clinic->field('name',__('Name'));
        });
        $show->field('date', __('Date'));
        $show->field('inject', __('Inject'));
        $show->field('ticket', __('Ticket'));
        $show->field('time', __('Time'));

        return $show;
    }

详情页面 屏蔽“编辑”按钮

 public static function boot()
    {
        parent::boot(); // TODO: Change the autogenerated stub
        static:: deleted(function (InfusionTicket $model) {
            Log::debug("模型删除");
            $clinicId = $model->clinic_id;
            $inject = $model->inject=='静脉输液'?'jmsy':'default';
            $date = $model->date;
            $dateFormat = Carbon::parse($date)->format('Y-m-d');
            $timeIndex = $model->time_index;
            Redis::select(2);
            $key = 'infusion-tickets:'.$clinicId.':'.$inject.':'.$dateFormat.':'.$timeIndex;
            Log::info($key);
            Redis::del($key);
        });
    }

在数据模型中 增加删除回调 删除redis值

Categories
php

migration 使用

为了laravel 数据库迁移 migration使用

按照某个model构建 mirgration

php artisan make:migration create_flights_table --create=flights

按照现有的数据库 dump一下

php artisan schema:dump

// Dump the current database schema and prune all existing migrations...
php artisan schema:dump --prune

migration文件例子

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateFlightsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('flights', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('airline');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('flights');
    }
}

执行migration

php artisan migrate

scheme详解

建表

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

Schema::create('users', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->string('email');
    $table->timestamps();
});

检查

if (Schema::hasTable('users')) {
    // The "users" table exists...
}

if (Schema::hasColumn('users', 'email')) {
    // The "users" table exists and has an "email" column...
}

指定连接

Schema::connection('sqlite')->create('users', function (Blueprint $table) {
    $table->id();
});

指定表储存引擎

Schema::create('users', function (Blueprint $table) {
    $table->engine = 'InnoDB';

    // ...
});

指定字符集

Schema::create('users', function (Blueprint $table) {
    $table->charset = 'utf8mb4';
    $table->collation = 'utf8mb4_unicode_ci';

    // ...
});

更改字段(和创建字段一样)

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

Schema::table('users', function (Blueprint $table) {
    $table->integer('votes');
});

表改名

Schema::rename($from, $to);

删除表

Schema::drop('users');

Schema::dropIfExists('users');

所有的字段类型

bigIncrements bigInteger binary boolean char dateTimeTz dateTime date decimal double enumfloat foreignId geometryCollection geometry id increments integer ipAddress json jsonb lineString longText macAddress mediumIncrements mediumInteger mediumText morphs multiLineString multiPoint multiPolygon nullableMorphs nullableTimestamps nullableUuidMorphs point polygon rememberToken set smallIncrements smallInteger softDeletesTz softDeletes stringtext timeTz time timestampTz timestamp timestampsTz timestampstinyIncrements tinyInteger unsignedBigInteger unsignedDecimal unsignedInteger unsignedMediumInteger unsignedSmallInteger unsignedTinyInteger uuidMorphs uuid year

更改字段

Schema::table('users', function (Blueprint $table) {
    $table->string('name', 50)->change();
});

字段改名

Schema::table('users', function (Blueprint $table) {
    $table->renameColumn('from', 'to');
});

舍弃字段

Schema::table('users', function (Blueprint $table) {
    $table->dropColumn('votes');
});

Schema::table('users', function (Blueprint $table) {
    $table->dropColumn(['votes', 'avatar', 'location']);
});
CommandDescription
$table->dropMorphs('morphable');Drop the morphable_id and morphable_type columns.
$table->dropRememberToken();Drop the remember_token column.
$table->dropSoftDeletes();Drop the deleted_at column.
$table->dropSoftDeletesTz();Alias of dropSoftDeletes() method.
$table->dropTimestamps();Drop the created_at and updated_at columns.
$table->dropTimestampsTz();Alias of dropTimestamps() method.

索引约束

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

Schema::table('users', function (Blueprint $table) {
    $table->string('email')->unique();
});

$table->unique('email');

$table->index(['account_id', 'created_at']);

$table->unique('email', 'unique_email');
CommandDescription
$table->primary('id');Adds a primary key.
$table->primary(['id', 'parent_id']);Adds composite keys.
$table->unique('email');Adds a unique index.
$table->index('state');Adds an index.
$table->spatialIndex('location');Adds a spatial index (except SQLite).

更改索引

$table->renameIndex('from', 'to')

删除索引(约束)

CommandDescription
$table->dropPrimary('users_id_primary');Drop a primary key from the “users” table.
$table->dropUnique('users_email_unique');Drop a unique index from the “users” table.
$table->dropIndex('geo_state_index');Drop a basic index from the “geo” table.
$table->dropSpatialIndex('geo_location_spatialindex');Drop a spatial index from the “geo” table (except SQLite).

外键约束

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

Schema::table('posts', function (Blueprint $table) {
    $table->unsignedBigInteger('user_id');

    $table->foreign('user_id')->references('id')->on('users');
});

//自动推测
Schema::table('posts', function (Blueprint $table) {
    $table->foreignId('user_id')->constrained();
});

Schema::table('posts', function (Blueprint $table) {
    $table->foreignId('user_id')->constrained('users');
});

外键级联

$table->foreignId('user_id')
      ->constrained()
      ->onUpdate('cascade')
      ->onDelete('cascade');

删除外键

$table->dropForeign(['user_id']);
Categories
php

eloquent 使用

简介eloquent 为laravel中的orm模块

以下代码为orm对象生成命令

php artisan make:model Flight //创建Flight orm 对象
php artisan make:model Flight --migration | -m //生成migration数据库迁移文件
# Generate a model and a FlightFactory class...
php artisan make:model Flight --factory
php artisan make:model Flight -f

# Generate a model and a FlightSeeder class...
php artisan make:model Flight --seed
php artisan make:model Flight -s

# Generate a model and a FlightController class...
php artisan make:model Flight --controller
php artisan make:model Flight -c

# Generate a model and a migration, factory, seeder, and controller...
php artisan make:model Flight -mfsc

生成的基本对象:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Flight extends Model
{
    //optional
    protected $table = 'my_flights';//指定表名
    protected $primaryKey = 'flight_id'; //指定主键
    public $incrementing = false; //主键生成模式
    protected $keyType = 'string';
 //主键数据类型
    public $timestamps = false;
//是否有create 和 update 时间
    protected $dateFormat = 'U';
 //日期格式
    const CREATED_AT = 'creation_date';
 //创建时间字段名
    const UPDATED_AT = 'updated_date';//更新时间字段名
    protected $connection = 'sqlite';
 //指定该orm数据库连接
    protected $fillable = [] //数组 可批量创建的字段
    protected $guard = [] //数组 不可批量创建的字段

    protected $attributes = [
   //字段默认值
        'delayed' => false,
    ];


}

查询方法:

Flight::all

use App\Models\Flight;

foreach (Flight::all() as $flight) {
    echo $flight->name;
}

查询构造器

$flights = Flight::where('active', 1)
               ->orderBy('name')
               ->take(10)
               ->get();

聚合函数

$count = Flight::where('active', 1)->count();

$max = Flight::where('active', 1)->max('price');

对象collection reject方法剔除取消的航班 (闭包返回true)

$flights = Flight::where('destination', 'Paris')->get();

$flights = $flights->reject(function ($flight) {
    return $flight->cancelled;
});

orm游标

use App\Models\User;

$users = User::cursor()->filter(function ($user) {
    return $user->id > 500;
});

子查询

use App\Models\Destination;
use App\Models\Flight;

return Destination::addSelect(['last_flight' => Flight::select('name')
    ->whereColumn('destination_id', 'destinations.id')
    ->orderByDesc('arrived_at')
    ->limit(1)
])->get();

查一条数据

use App\Models\Flight;

// Retrieve a model by its primary key...
$flight = Flight::find(1);

// Retrieve the first model matching the query constraints...
$flight = Flight::where('active', 1)->first();

// Alternative to retrieving the first model matching the query constraints...
$flight = Flight::firstWhere('active', 1);

查到一条或者(闭包)

model = Flight::where('legs', '>', 3)->firstOr(function () {
    // ...
});

查询报notFound fail方法

$flight = Flight::findOrFail(1);

$flight = Flight::where('legs', '>', 3)->firstOrFail();

静态创建

use App\Models\Flight;

// Retrieve flight by name or create it if it doesn't exist...
$flight = Flight::firstOrCreate([
    'name' => 'London to Paris'
]);

// Retrieve flight by name or create it with the name, delayed, and arrival_time attributes...
$flight = Flight::firstOrCreate(
    ['name' => 'London to Paris'],
    ['delayed' => 1, 'arrival_time' => '11:30']
);

// Retrieve flight by name or instantiate a new Flight instance...
$flight = Flight::firstOrNew([
    'name' => 'London to Paris'
]);

// Retrieve flight by name or instantiate with the name, delayed, and arrival_time attributes...
$flight = Flight::firstOrNew(
    ['name' => 'Tokyo to Sydney'],
    ['delayed' => 1, 'arrival_time' => '11:30']
);

对象创建

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Flight;
use Illuminate\Http\Request;

class FlightController extends Controller
{
    /**
     * Store a new flight in the database.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        // Validate the request...

        $flight = new Flight;

        $flight->name = $request->name;

        $flight->save();
    }
}

对象更新

use App\Models\Flight;

$flight = Flight::find(1);

$flight->name = 'Paris to London';

$flight->save();

批量更新

Flight::where('active', 1)
      ->where('destination', 'San Diego')
      ->update(['delayed' => 1]);

对象填充数据

$flight->fill(['name' => 'Amsterdam to Frankfurt']);

按条件更新或创建

$flight = Flight::updateOrCreate(
    ['departure' => 'Oakland', 'destination' => 'San Diego'],//条件
    ['price' => 99, 'discounted' => 1] //数据
);
Flight::upsert([
    ['departure' => 'Oakland', 'destination' => 'San Diego', 'price' => 99],
    ['departure' => 'Chicago', 'destination' => 'New York', 'price' => 150]
], ['departure', 'destination'], ['price']);

删除

use App\Models\Flight;

$flight = Flight::find(1);

$flight->delete();
Flight::destroy(1);

Flight::destroy(1, 2, 3);

Flight::destroy([1, 2, 3]);

Flight::destroy(collect([1, 2, 3]));

查询删除

$deletedRows = Flight::where('active', 0)->delete();

逻辑删除

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Flight extends Model
{
    use SoftDeletes; //多一个deleted_at字段
}

迁移文件

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Facades\Schema;

Schema::table('flights', function (Blueprint $table) {
    $table->softDeletes();
});

Schema::table('flights', function (Blueprint $table) {
    $table->dropSoftDeletes();
});

检查是是否被软删除

if ($flight->trashed()) {
    //
}

还原逻辑删除的数据

$flight->restore();
Flight::withTrashed()
        ->where('airline_id', 1)
        ->restore();
$flight->history()->restore();

强制物理删除

$flight->forceDelete();

和软删除的数据一起查询

$flights = Flight::withTrashed()
                ->where('account_id', 1)
                ->get();

只查询软删除的数据

$flights = Flight::onlyTrashed()
                ->where('airline_id', 1)
                ->get();

对象复制replicate

use App\Models\Address;

$shipping = Address::create([
    'type' => 'shipping',
    'line_1' => '123 Example Street',
    'city' => 'Victorville',
    'state' => 'CA',
    'postcode' => '90001',
]);

$billing = $shipping->replicate()->fill([
    'type' => 'billing'
]);

$billing->save();
Categories
php

Laravel redis使用

laravel 使用redis 需要先安装redis包

composer require predis/predis

redis的配置文件是:config/database.php
 
 'redis' => [
 
        'client' => 'predis', //指定redis驱动为predis
 
        'default' => [
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD',null),
            'port' => env('REDIS_PORT', 6379),
            'database' => 0,
        ],
 
    ],

在 .env 配置具体参数
REDIS_CLIENT=predis
    //也可在这里指定redis驱动为predis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
操作代码

use Illuminate\Support\Facades\Redis;

//set存数据 创建一个 key 并设置value 
Redis::set('key','value'); 
 
//get命令用于获取指定 key 的值,key不存在,返回null,如果key储存的值不是字符串类型,返回一个错误。
var_dump(Redis::get('key'));
 
//del 删除 成功删除返回 true, 失败则返回 false
Redis::del('key');
 
//mset存储多个 key 对应的 value
$array= array(
		'user1'=>'张三',
		'user2'=>'李四',
		'user3'=>'王五'
);
redis::mset($array); // 存储多个 key 对应的 value
 
// Mget返回所有(一个或多个)给定 key 的值,给定的 key 里面,key 不存在,这个 key 返回特殊值 nil
 
var_dump(redis::mget (array_keys( $array))); //获取多个key对应的value
 
//Strlen 命令用于获取指定 key 所储存的字符串值的长度。当 key存储不是字符串,返回错误。
var_dump(redis::strlen('key'));
 
//substr 获取第一到第三位字符
var_dump(Redis::substr('key',0,2));
 
//根据键名模糊搜索
var_dump(Redis::keys('use*'));//模糊搜索
 
//获取缓存时间
Redis::ttl('str2');//获取缓存时间
 
//exists检测是否存在某值
Redis::exists ( 'foo' ) ; //true

redis get

 'user' => Redis::get('user:profile:'.$id)

redis lrange

$values = Redis::lrange('names', 5, 10);

命令模式

$values = Redis::command('lrange', ['name', 5, 10]);

指定连接返回redis对象

$redis = Redis::connection('connection-name');

redis 事务


Redis::transaction(function ($redis) {
    $redis->incr('user_visits', 1);
    $redis->incr('total_visits', 1);
});

pipeline模式

Redis::pipeline(function ($pipe) {
    for ($i = 0; $i < 1000; $i++) {
        $pipe->set("key:$i", $i);
    }
});

redis消息队列(用laravel command 生成监听类)

消息订阅

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;

class RedisSubscribe extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'redis:subscribe';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Subscribe to a Redis channel';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        Redis::subscribe(['test-channel'], function ($message) {
            echo $message;
        });
    }
}

消息发布

 Redis::publish('test-channel', json_encode([
        'name' => 'Adam Wathan'
    ]));