标签归档:laravel

laravel-websockets使用教程

后端

1、安装扩展

composer require beyondcode/laravel-websockets

发布迁移

php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="migrations"
php artisan migrate

发布配置

php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="config"

配置 .env

PUSHER_APP_ID=
PUSHER_APP_KEY=your-pusher-key
PUSHER_APP_SECRET=
PUSHER_HOST=127.0.0.1
PUSHER_PORT=6001
PUSHER_SCHEME=http
PUSHER_APP_CLUSTER=mt1

2、确保 config/app.php 文件,providers 配置中没有注释依赖项。如果有不能解释的报错,可以确认一下。

3、创建事件

php artisan make:event DemoEvent

修改类 App\Events\DemoEvent ,注意添加实现 ShouldBroadcast

<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class DemoEvent implements ShouldBroadcast # 添加实现类
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public string $message;

    // 使用成员变量,前端 listen 事件名为 `DemoEvent`
    // public $broadcastAs = 'DemoEvent';

    public function __construct()
    {
        $this->message = 'Hello friend';
    }

    // 使用成员方法,前端 listen 事件名为 `.DemoEvent`
    public function broadcastAs() {
        return 'DemoEvent';
    }

    public function broadcastOn()
    {
        // PrivateChannel 需要登录,改为 Channel
        // channel 名称本文改为 public
        return new Channel('public');
    }
}

如果不指定 broadcastAs,默认事件名为类名,即: App\Events\DemoEvent

4、运行服务

php81 artisan websockets:serve

5、调用/下发事件

# 以下都行
DemoEvent::dispatch();
broadcast(new DemoEvent())->toOthers();
broadcast(new DemoEvent());
event(new DemoEvent());

6、DASHBOARD

访问 /laravel-websockets 可以打开 dashboard 和调试,地址可以在 config/websockets.php 中配置

前端

1、以 vue 为例,安装扩展

npm i -D laravel-echo pusher-js

2、添加 laravel-echo.js 文件

import Echo from "laravel-echo";
import Pusher from "pusher-js";
window.Pusher = Pusher;

window.Echo = new Echo({
  broadcaster: "pusher",
  key: "your-pusher-key",
  wsHost: window.location.hostname,
  wsPort: 6001,
  forceTLS: false,
  disableStats: true,
  cluster: "mt1",
});

main.js 中引入

import "./laravel-echo";

3、在合适的位置订阅消息

window.Echo.channel("public").listen(".DemoEvent", (e) => {
  console.log(e.message);
});

此处 DemoEvent 为事件名,在后端可以通过 broadcastAs 来指定:

  1. 如果没有指定,默认为类名: App\\Events\\DemoEvent
  2. 如果使用成员变量:DemoEvent
  3. 如果使用成员方法:.DemoEvent
继续阅读

php 框架执行存储过程(stored procedure) 并获取返回

laravel

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use PDO;

class TestController extends Controller
{
    public function index()
    {
        $pdo = DB::getPdo();
        $int = 1;
        $res = 0;
        $stmt = $pdo->prepare("EXEC dbo.test :int,:res");
        $stmt->bindParam(':int', $res, PDO::PARAM_INT);
        $stmt->bindParam(':res', $res, PDO::PARAM_STR | PDO::PARAM_INPUT_OUTPUT, 400);
        $stmt->execute();
        dd($res);
    }
}

参考:

  • https://stackoverflow.com/questions/71321858/api-laravel-call-store-procedure-with-in-and-out-parameter-using-oci8-or-pdo
  • https://laracasts.com/discuss/channels/general-discussion/running-stored-procedures

thinkphp 5.0

tp5 需要修改原码才可以使用:

  • 找到文件 thinkphp/library/think/db/Connection.php
  • 第 388 行,在 catch (\PDOException $e) 内,修改为如下代码:
    if ($procedure == true) { return; } elseif ($this->isBreak($e)) { return $this->close()->query($sql, $bind, $master, $pdo); }

控制器执行:

<?php

namespace app\api\controller;

use PDO;
use think\Db;

class Test extends Common {
    public function index() {
        $int = 1;
        $res = 1;
        Db::query('exec test :int,:res', [
            'int' => $int,
            'res' => [&$res, PDO::PARAM_STR | PDO::PARAM_INPUT_OUTPUT, 4000],
        ]);
        print_r($res);
    }
}

参考:

  • https://blog.csdn.net/Drug_/article/details/95474776

以上示例使用的存储过程如下:

ALTER PROC [dbo].[test]
-- 创建:CREATE PROC [dbo].[test]
 @IntInput int,
 @StrResult varchar(20) out
as
begin
         if (@IntInput>1)
           Set
        @StrResult = '>1'
        else 
            Set
        @StrResult = '<=1'
end

SQL 执行:

declare @strResult varchar(20)
exec test -1,@strResult output
print @strResult

lumen 使用 redis

安装扩展

composer require predis/predis
composer require illuminate/redis

引入redis支持

$app->register(Illuminate\Redis\RedisServiceProvider::class);

启用redis辅助函数

$app->withFacades();
$app->withEloquent();

配置redis服务器参数

默认系统是调用的.env里的redis配置文件,但是一般安装后没有这些参数,可以查看文件路径vendor/laravel/lumen-framework/config/database.php中查看有哪些参数需要配置,例如,我的.env文件需要配置

REDIS_HOST=192.168.1.41
REDIS_PORT=7000
REDIS_PASSWORD=123456

laravel 5.5 安装使用 passport

使用 Composer 安装 Passport :

composer require laravel/passport:~4.0

Laravel 5.6 已经发布,最新的 laravel/passport 版本为 5.0 适配 Laravel 5.6,所以我们需要使用 Laravel 5.5 的适配版本 4.0

如果安装过程中遇到 paragonie/random_compat 版本冲突的问题,可以先执行以下命令将其降级为 2.0 的版本。

composer require paragonie/random_compat:^2.0

继续阅读

faker 常见填充的类型

[
    // 个人信息  
    '姓名 name' => $faker->name,
    '姓 lastName' => $faker->lastName,
    '名 firstName' => $faker->firstName,
    '手机 mobile' => $faker->phoneNumber,
    '信用卡信息数组 creditCardDetails'=> $faker->creditCardDetails,

    // 地理位置  
    '纬度 latitude' =>$faker->latitude,
    '经度 longitude' =>$faker->longitude,
    '国家 country' => $faker->country,
    '国家代码 countryCode' => $faker->countryCode,
    '邮政编码:postcode'=> $faker->postcode,
    '地址 address' => $faker->address,
    '城市 city' => $faker->city,
    '省 state'=> $faker->state,
    '省简称 stateAbbr' =>$faker->stateAbbr,
    '区 area' => $faker->area,
    '街道 streetAddress' => $faker->streetAddress,
    '邮编 postcode' => $faker->postcode,

    // 公司,银行,广告语  
    '公司后缀 companySuffix'=> $faker->companySuffix,
    '公司 company'=> $faker->company,
    '银行 bank' => $faker->bank,
    '广告语 catchPhrase'=>$faker->catchPhrase,

    // 时间  
    'unixTime' => $faker->unixTime,
    'year' => $faker->year,
    'month' => $faker->month,
    'dayOfMonth'=> $faker->dayOfMonth,
    'date' =>$faker->date,
    'time' =>$faker->time,

    //互联网  
    'domainName' => $faker->domainName,
    'companyEmail' => $faker->companyEmail,
    'email' => $faker->email,
    'userName' => $faker->userName,
    'password' => $faker->password,
    'url' => $faker->url,
    'ipv4' => $faker->ipv4,
    'ipv6' => $faker->ipv6,
    'localIpv4' => $faker->localIpv4,
    'macAddress' => $faker->macAddress,
    'userAgent' => $faker->userAgent,

    // 杂项  
    '罗马数字century' => $faker->century,
    '颜色hexcolor' =>$faker->hexcolor,
    'mimeType'=>$faker->mimeType,
    '文件后缀fileExtension'=>$faker->fileExtension,
    'img' => $faker->image,
    'imgurl' => $faker->imageUrl,
    'uuid'   => $faker->uuid,
    'sha1' => $faker->sha1,
    'sha256' => $faker->sha256,
    'md5'=> $faker->md5,

    //文本内容  
    '单词 word' => $faker->word,
    '单词 words' => $faker->words ( 5, true ),
    '短标题 sentence' => $faker->sentence,
    '内容 content' => $faker->text ( 500 ) ,
    '内容 realText' => $faker->realText(100),
]

laravel使用php-redis和prefix防止redis键名冲突

首先需要安装 php-redis

apt install php-redis

config/database.php 中,修改 redisclientphpredis,并在 default 中添加 prefix => env('REDIS_PREFIX', ''),

最后在 .env 中配置 REDIS_PREFIX 即可实现隔离。

但是,直接使用 redis 要比使用 php-redis 效率更高。