月度归档: 2022 年 4 月

  • 在 Laravel 6、LightHouse 5、Module 中使用 @rules 指令时,应用 exists 规则时的本地化实现

    在 Laravel 6、LightHouse 5、Module 中使用 @rules 指令时,应用 exists 规则时的本地化实现

    1、当语言区域为 en 时,当验证的参数不存在时,响应:The selected theme id is invalid.。如图1
    当语言区域为 en 时,当验证的参数不存在时,响应:The selected theme id is invalid.
    图1
    
    
    {
      "errors": [
        {
          "message": "Validation failed for the field [onlineStoreThemeEditorSessionCreate].",
          "extensions": {
            "validation": {
              "themeId": [
                "The selected theme id is invalid."
              ]
            },
            "category": "validation"
          },
          "locations": [
            {
              "line": 2,
              "column": 3
            }
          ],
          "path": [
            "onlineStoreThemeEditorSessionCreate"
          ],
          "trace": ...
        }
      ],
      "data": {
        "onlineStoreThemeEditorSessionCreate": null
      }
    }
    
    
    
    2、当语言区域为 zh_CN 时,当验证的参数不存在时,响应:所选的theme id无效。预期为:所选的主题ID无效。如图2
    当语言区域为 zh_CN 时,当验证的参数不存在时,响应:所选的theme id无效。预期为:所选的主题ID无效。
    图2
    
    
    {
      "errors": [
        {
          "message": "Validation failed for the field [onlineStoreThemeEditorSessionCreate].",
          "extensions": {
            "validation": {
              "themeId": [
                "所选的theme id无效。"
              ]
            },
            "category": "validation"
          },
          "locations": [
            {
              "line": 2,
              "column": 3
            }
          ],
          "path": [
            "onlineStoreThemeEditorSessionCreate"
          ],
          "trace": ...
        }
      ],
      "data": {
        "onlineStoreThemeEditorSessionCreate": null
      }
    }
    
    
    
    3、查看 GraphQL 代码实现,/Modules/ThemeStore/Resources/graphql/theme_editor.graphql
    
    
    extend type Mutation {
        "创建主题编辑会话"
        onlineStoreThemeEditorSessionCreate(themeId: ID! @rules(apply: ["exists:theme_asset,theme_id"])): ThemeEditorSessionCreatePayload @field(resolver: "Modules\\ThemeStore\\Resolver\\ThemeEditor\\CreateThemeEditorSessionResolver")
    }
    
    type ThemeEditorSessionCreatePayload
    {
        "会话"
        session: Session!
    }
    
    
    
    
    
    4、查看 语言文件 ,/Modules/ThemeStore/Resources/lang/zh_CN/validation.php,已经指定了 theme_id 的自定义属性名称,但是,并未生效
    <pre class="wp-block-syntaxhighlighter-code">
    
    <?php
    
    return [
    
        'attributes' => [
            'theme_id' => '主题ID',
        ],
    ];
    
    
    </pre>
    
    5、即使将此配置放至语言文件 /resources/lang/zh_CN/validation.php 中,仍然未生效,响应:所选的theme_id无效。但是,其默认是使用的此语言文件的配置。将验证规则消息放在任何语言的 validation.php 中名为 attributes 的键中,验证消息的 :attribute 部分不会被翻译(模块上下文)。
    <pre class="wp-block-syntaxhighlighter-code">
    
    <?php
    
    return [
    
    	'exists' => '所选的:attribute无效。',
    
        'attributes' => [
            'theme_id' => '主题ID',
        ],
    ];
    
    
    </pre>
    
    6、在 Laravel v8.7.90、nwidart/laravel-modules 8.2.0 中,编辑 /resources/lang/zh_CN/validation.php ,attributes 会生效。
    
    
        /**
         * 显示创建博客文章的表单
         *
         * @return Response
         */
        public function create(Request $request)
        {
            $validator = Validator::make($request->all(), [
                'theme_id' => 'required|exists:users,id',
            ]);
    
            if ($validator->fails()) {
                dd($validator->errors());
            }
    
            // 保存博客文章…
    
            return view('blog::post.create');
        }
    
    
    
    <pre class="wp-block-syntaxhighlighter-code">
    
    <?php
    return [
        'exists' => '所选的:attribute无效。resources',
    
        'attributes' => [
            'theme_id' => '主题ID',
        ],
    ];
    
    
    </pre>
    
    
    
    Illuminate\Support\MessageBag {#361 ▼
      #messages: array:1 [▼
        "theme_id" => array:1 [▼
          0 => "所选的主题ID无效。resources"
        ]
      ]
      #format: ":message"
    }
    
    
    
    7、决定在当前版本:Laravel v6.20.43、nwidart/laravel-modules 7.3.0 中,模拟步骤6的实现。以确定是否与框架、模块包的版本有关,进而导致在应用的根目录中,attributes 不生效的问题。确定是无关的。那么原因在于 LightHouse 5。
    <pre class="wp-block-syntaxhighlighter-code">
    
    <?php
    return [
        'array' => ':attribute必须是一个数组。',
    
        'attributes' => [
            'filter' => '过滤器'
        ],
    ];
    
    
    </pre>
    
    
    
    {
      "message": "The given data was invalid.",
      "errors": {
        "filter": [
          "过滤器必须是一个数组。"
        ]
      },
      "status_code": 422,
      "debug": {
        "line": 385,
        "file": "E:\\wwwroot\\object\\vendor\\laravel\\framework\\src\\Illuminate\\Validation\\Validator.php",
        "class": "Illuminate\\Validation\\ValidationException",
        "trace": ...
      }
    }
    
    
    
    8、参考:https://github.com/nuwave/lighthouse/issues/1773 ,虽然已经在 @rules 指令上实现了翻译功能,但是实现得不够彻底。即验证属性未支持。开发者建议:https://lighthouse-php.com/master/security/validation.html#validator-classes 。支持通过任意 PHP 代码定义规则。 9、暂时不准备编写一个自定义规则。决定在非英语环境下,属性名未翻译为对应的语言,暂且接受。且语言文件在根目录下,不在对应的模块目录下。  
  • 在 Laravel 6、LightHouse 5、PHPUnit 中编写测试 Mutation,删除缓存中的数据实现

    在 Laravel 6、LightHouse 5、PHPUnit 中编写测试 Mutation,删除缓存中的数据实现

    1、在程序实现中,先请求 API,生成缓存标识。然后再请求 API,删除缓存标识。如图1
    在程序实现中,先请求 API,生成缓存标识。然后再请求 API,删除缓存标识。
    图1
    2、如果要在测试中通过,前提是必须存在一个明确的缓存标识,以用于删除请求的参数。 3、参考网址:https://learnku.com/laravel/t/22690 。使用 TDD 测试驱动开发来构建 Laravel REST API。测试删除路由,其是先直接操作数据库,生成一条记录,然后再调用 HTTP API,测试删除操作。
    
    
    // 测试删除路由
    public function testDelete(){
        $token = $this->authenticate();
        $recipe = Recipe::create([
            'title' => 'Jollof Rice',
            'procedure' => 'Parboil rice, get pepper and mix, and some spice and serve!'
        ]);
        $this->user->recipes()->save($recipe);
        $response = $this->withHeaders([
            'Authorization' => 'Bearer '. $token,
        ])->json('POST',route('recipe.delete',['recipe' => $recipe->id]));
        $response->assertStatus(200);
        // 断言没有食谱
        $this->assertEquals(0,$this->user->recipes()->count());
    }
    
    
    
    
    4、因此,决定也如此设计。先直接操作缓存,生成对应的缓存标识,然后再执行 HTTP API 请求测试。
    
    
    
        public function testDeleteThemeEditorCode(): void
        {
            $random = Str::random(36);
            $value = [
                'theme_id' => 'vogue'
            ];
            Cache::tags([ThemeEditorResolver::TAG_THEME_EDITOR, ThemeEditorResolver::TAG_THEME_EDITOR_CODE])->put($random, $value, 86400);
    
            $response = $this->graphQL('
                mutation DeleteThemeEditorCode($themeEditorCode: String!) {
                    onlineStoreThemeEditorCodeDelete(themeEditorCode: $themeEditorCode) {
                        deletedThemeEditorCode
                    }
                }
            ', [
                'themeEditorCode' => $random,
            ]);
    
            $response->assertJson(
                [
                    'data' => [
                        'onlineStoreThemeEditorCodeDelete' => [
                            'deletedThemeEditorCode' => $random
                        ],
                    ],
                ]
            );
        }
    
    
    
    
    5、运行测试,测试通过。如图2
    运行测试,测试通过
    图2
    
    
    PS E:\wwwroot\object> .\vendor\bin\phpunit .\Modules\ThemeStore\Tests\Functional\GraphQl\ThemeEditorGraphQlApiTest.php
    PHPUnit 7.5.20 by Sebastian Bergmann and contributors.
    
    ..                                                                  2 / 2 (100%)
    
    Time: 1.31 seconds, Memory: 72.00 MB
    
    OK (2 tests, 4 assertions)
    
    
    
  • 在 Laravel 6、LightHouse 5、Module 中,自定义验证规则的使用

    在 Laravel 6、LightHouse 5、Module 中,自定义验证规则的使用

    1、现阶段需要在 GraphQL API 中实现一个删除缓存标识的接口。参考 Shopify 的示例。当缓存标识不存在时,响应失败。如图1
    现阶段需要在 GraphQL API 中实现一个删除缓存标识的接口。参考 Shopify 的示例。当缓存标识不存在时,响应失败
    图1
    
    
    mutation DeleteThemeSessionId($sessionId: String!) {
      onlineStoreEditorSessionDelete(sessionId: $sessionId) {
        deletedSessionId
        userErrors {
          field
          message
          __typename
        }
        __typename
      }
    }
    
    
    
    
    
    
    {
      "sessionId": "H9Mc8FwH5Eu5LR37XAzsehh4"
    }
    
    
    
    
    
    {
      "data": {
        "onlineStoreEditorSessionDelete": {
          "deletedSessionId": null,
          "userErrors": [
            {
              "field": [
                "sessionId"
              ],
              "message": "在线商店编辑器访问不存在",
              "__typename": "UserError"
            }
          ],
          "__typename": "OnlineStoreEditorSessionDeletePayload"
        }
      },
      "extensions": {
        "cost": {
          "requestedQueryCost": 10,
          "actualQueryCost": 10,
          "throttleStatus": {
            "maximumAvailable": 1000,
            "currentlyAvailable": 990,
            "restoreRate": 50
          }
        }
      }
    }
    
    
    
    2、由于验证此缓存标识是否存在的规则,会用于大量的 API 中。最张决定自定义验证规则,以复用此验证规则。 3、由于是在模块中编写验证规则。module:make-rule Create a new validation rule for the specified module.
    <pre class="wp-block-syntaxhighlighter-code">
    
    PS E:\wwwroot\object> php artisan help module:make-rule
    Description:
      Create a new validation rule for the specified module.
    
    Usage:
      module:make-rule <name> [<module>]
    
    Arguments:
      name                  The name of the rule class.
      module                The name of module will be used.
    
    Options:
      -h, --help            Display this help message
      -q, --quiet           Do not output any message
      -V, --version         Display this application version
          --ansi            Force ANSI output
          --no-ansi         Disable ANSI output
      -n, --no-interaction  Do not ask any interactive question
          --env[=ENV]       The environment the command should run under
      -v|vv|vvv, --verbose  Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
    PS E:\wwwroot\object> php artisan module:make-rule ThemeEditor/ThemeEditorCodeExistsRule ThemeStore
    Created : E:/wwwroot/object/Modules/ThemeStore/Rules/ThemeEditor/ThemeEditorCodeExistsRule.php
    PS E:\wwwroot\object>
    
    </pre>
    
    4、编辑规则类,判断缓存标识是否存在。/Modules/ThemeStore/Rules/ThemeEditor/ThemeEditorCodeExistsRule.php
    <pre class="wp-block-syntaxhighlighter-code">
    
    <?php
    
    namespace Modules\ThemeStore\Rules\ThemeEditor;
    
    use Illuminate\Contracts\Validation\Rule;
    use Illuminate\Support\Facades\Cache;
    use Modules\ThemeStore\Resolver\ThemeEditor\ThemeEditorResolver;
    
    class ThemeEditorCodeExistsRule implements Rule
    {
        /**
         * Determine if the validation rule passes.
         *
         * @param  string  $attribute
         * @param  mixed  $value
         * @return bool
         */
        public function passes($attribute, $value)
        {
            return Cache::tags([ThemeEditorResolver::TAG_THEME_EDITOR, ThemeEditorResolver::TAG_THEME_EDITOR_CODE])->has($value);
        }
    
        /**
         * Get the validation error message.
         *
         * @return string
         */
        public function message()
        {
            return 'The validation error message.';
        }
    }
    
    
    </pre>
    
    5、编辑 /ThemeStore/Resources/graphql/theme_editor.graphql 。使用 @rules 指令,通过完全限定的类名引用自定义验证规则:ThemeEditorCodeExistsRule
    
    
    extend type Mutation {
        ...
        "删除主题编辑标识"
        onlineStoreThemeEditorCodeDelete(themeEditorCode: String! @rules(apply: ["Modules\\ThemeStore\\Rules\\ThemeEditor\\ThemeEditorCodeExistsRule"])): ThemeEditorCodeDeletePayload @field(resolver: "Modules\\ThemeStore\\Resolver\\ThemeEditor\\DeleteThemeEditorCodeResolver")
    }
    
    type ThemeEditorCodeDeletePayload
    {
        deletedThemeEditorCode: String
    }
    
    
    
    
    6、新生成了一个缓存标识:vRYbn7NQiEWMbH2G6sXB8AE4aoBIk4JQOw2p,先测试验证失败的情况。
    
    
    mutation {
      onlineStoreThemeEditorCodeDelete(themeEditorCode: "vRYbn7NQiEWMbH2G6sXB8AE4aoBIk4JQOw2p0") {
        deletedThemeEditorCode
      }
    }
    
    
    
    
    
    
    {
      "errors": [
        {
          "message": "Validation failed for the field [onlineStoreThemeEditorCodeDelete].",
          "extensions": {
            "validation": {
              "themeEditorCode": [
                "The validation error message."
              ]
            },
            "category": "validation"
          },
          "locations": [
            {
              "line": 2,
              "column": 3
            }
          ],
          "path": [
            "onlineStoreThemeEditorCodeDelete"
          ],
          "trace": [
    		...
    	  ]
        }
      ],
      "data": {
        "onlineStoreThemeEditorCodeDelete": null
      }
    }
    
    
    
    7、新建模块下的 /Modules/ThemeStore/Resources/lang/en/validation.php 语言文件。
    <pre class="wp-block-syntaxhighlighter-code">
    
    <?php
    
    return [
        'custom' => [
            'theme_editor_code' => [
                'theme_editor_code_exists_rule' => 'The selected :attribute is invalid.',
            ],
        ],
    
        'attributes' => [],
    ];
    
    
    </pre>
    
    8、编辑规则类,/Modules/ThemeStore/Rules/ThemeEditor/ThemeEditorCodeExistsRule.php。从翻译文件中返回一个错误消息,从 message 方法中调用辅助函数 trans。
    <pre class="wp-block-syntaxhighlighter-code">
    
    <?php
    
    namespace Modules\ThemeStore\Rules\ThemeEditor;
    
    use Illuminate\Contracts\Validation\Rule;
    use Illuminate\Support\Facades\Cache;
    use Modules\ThemeStore\Resolver\ThemeEditor\ThemeEditorResolver;
    
    class ThemeEditorCodeExistsRule implements Rule
    {
        /**
         * Determine if the validation rule passes.
         *
         * @param  string  $attribute
         * @param  mixed  $value
         * @return bool
         */
        public function passes($attribute, $value)
        {
            return Cache::tags([ThemeEditorResolver::TAG_THEME_EDITOR, ThemeEditorResolver::TAG_THEME_EDITOR_CODE])->has($value);
        }
    
        /**
         * Get the validation error message.
         *
         * @return string
         */
        public function message()
        {
            return trans('theme_store::validation.custom.theme_editor_code.theme_editor_code_exists_rule');
        }
    }
    
    
    </pre>
    
    9、再次测试验证失败的情况。The validation error message. 已经被替换为:The selected theme editor code is invalid.。如图2
    再次测试验证失败的情况。The validation error message. 已经被替换为:The selected theme editor code is invalid.
    图2
    
    
    mutation {
      onlineStoreThemeEditorCodeDelete(themeEditorCode: "vRYbn7NQiEWMbH2G6sXB8AE4aoBIk4JQOw2p0") {
        deletedThemeEditorCode
      }
    }
    
    
    
    
    
    
    {
      "errors": [
        {
          "message": "Validation failed for the field [onlineStoreThemeEditorCodeDelete].",
          "extensions": {
            "validation": {
              "themeEditorCode": [
                "The selected theme editor code is invalid."
              ]
            },
            "category": "validation"
          },
          "locations": [
            {
              "line": 2,
              "column": 3
            }
          ],
          "path": [
            "onlineStoreThemeEditorCodeDelete"
          ],
          "trace": [
    		...
    	  ]
        }
      ],
      "data": {
        "onlineStoreThemeEditorCodeDelete": null
      }
    }
    
    
    
    10、新建模块下的 /Modules/ThemeStore/Resources/lang/zh_CN/validation.php 语言文件。
    <pre class="wp-block-syntaxhighlighter-code">
    
    <?php
    
    return [
        'custom' => [
            'theme_editor_code' => [
                'theme_editor_code_exists_rule' => '所选的主题编辑标识无效。',
            ],
        ],
    
        'attributes' => [],
    ];
    
    
    </pre>
    
    11、当前语言区域被设置为:zh_CN 时,测试失败的响应,响应信息为中文。符合预期。如图3
    当前语言区域被设置为:zh_CN 时,测试失败的响应,响应信息为中文。符合预期
    图3
    
    
    {
      "errors": [
        {
          "message": "Validation failed for the field [onlineStoreThemeEditorCodeDelete].",
          "extensions": {
            "validation": {
              "themeEditorCode": [
                "所选的主题编辑标识无效。"
              ]
            },
            "category": "validation"
          },
          "locations": [
            {
              "line": 2,
              "column": 3
            }
          ],
          "path": [
            "onlineStoreThemeEditorCodeDelete"
          ],
          "trace": [
    		...
    	  ]
        }
      ],
      "data": {
        "onlineStoreThemeEditorCodeDelete": null
      }
    }
    
    
    
    12、可将 /Modules/ThemeStore/Resources/lang/en/validation.php 复制为 /Modules/ThemeStore/Resources/lang/en_US/validation.php。当语言区域设置为 en_US 时,/en_US/validation.php 的优先级高于 /en/validation.php。如果在 /en_US/validation.php 中查找不到,则会从 /en/validation.php 查找。测试失败的响应。
    <pre class="wp-block-syntaxhighlighter-code">
    
    <?php
    
    return [
        'custom' => [],
    
        'attributes' => [],
    ];
    
    
    </pre>
    
    
    
    {
      "errors": [
        {
          "message": "Validation failed for the field [onlineStoreThemeEditorCodeDelete].",
          "extensions": {
            "validation": {
              "themeEditorCode": [
                "The selected theme editor code is invalid."
              ]
            },
            "category": "validation"
          },
          "locations": [
            {
              "line": 2,
              "column": 3
            }
          ],
          "path": [
            "onlineStoreThemeEditorCodeDelete"
          ],
          "trace": ...
        }
      ],
      "data": {
        "onlineStoreThemeEditorCodeDelete": null
      }
    }
    
    
    
    13、注:theme_store 的名称源于 /ThemeStore/Providers/ThemeStoreServiceProvider.php
    
    
    private $moduleNameLower = 'theme_store';
    
    
    
    14、测试验证通过的情况,符合预期。如图4
    测试验证通过的情况,符合预期
    图4
    
    
    mutation {
      onlineStoreThemeEditorCodeDelete(themeEditorCode: "vRYbn7NQiEWMbH2G6sXB8AE4aoBIk4JQOw2p") {
        deletedThemeEditorCode
      }
    }
    
    
    
    
    
    
    {
      "data": {
        "onlineStoreThemeEditorCodeDelete": {
          "deletedThemeEditorCode": "vRYbn7NQiEWMbH2G6sXB8AE4aoBIk4JQOw2p"
        }
      }
    }
    
    
    
     
  • 在 Windows 10、Laravel 6 中使用 PhpRedis PHP 扩展,存储与获取缓存数据

    在 Windows 10、Laravel 6 中使用 PhpRedis PHP 扩展,存储与获取缓存数据

    1、在将 Redis 与 Laravel 一起使用的时候,有两种方案,一种是安装 PhpRedis PHP 扩展,一种是通过 Composer 安装 predis / predis 包。不过 Predis 已被该软件包的原始作者遗弃,并可能在将来的版本中从 Laravel 中删除。最终决定使用第一种方案。编辑 .env 文件,设置缓存驱动为 redis。以测试 Redis 的使用。
    
    
    CACHE_DRIVER=redis
    
    REDIS_HOST=127.0.0.1
    REDIS_PASSWORD=null
    REDIS_PORT=6378
    REDIS_DB=4
    REDIS_CACHE_DB=5
    
    
    
    2、在首页控制器方法中,在缓存中存储与获取数据
    <pre class="wp-block-syntaxhighlighter-code">
    
    <?php
    
    namespace App\Http\Controllers;
    
    use Illuminate\Support\Facades\Cache;
    
    class IndexController extends Controller
    {
        public function index()
        {
            Cache::put('key', 'value');
            $value = Cache::get('key');
            dd($value);
        }
    }
    
    
    </pre>
    
    3、浏览首页,报错:LogicException Please make sure the PHP Redis extension is installed and enabled.请确保已安装并启用 PHP Redis 扩展。如图1
    浏览首页,报错:LogicException Please make sure the PHP Redis extension is installed and enabled.请确保已安装并启用 PHP Redis 扩展
    图1
    4、Laravel 官方建议通过 PECL 安装并使用 PhpRedis PHP 扩展。打开网址:https://pecl.php.net/package/redis 。选择 Version 5.3.7。下载 redis 5.3.7 for Windows。如图2
    Laravel 官方建议通过 PECL 安装并使用 PhpRedis PHP 扩展。打开网址:https://pecl.php.net/package/redis 。选择 Version 5.3.7。下载 redis 5.3.7 for Windows
    图2
    5、查看 phpinfo,Thread Safety 的值为 enabled。因此,选择 7.4 Thread Safe (TS) x64。如图3
    查看 phpinfo,Thread Safety 的值为 enabled。因此,选择 7.4 Thread Safe (TS) x64
    图3
    6、复制 php_redis.dll 至 C:\php-7.4.27\ext\php_redis.dll 7、编辑 php.ini 文件,启用 PhpRedis PHP 扩展。重启 PHP
    
    
    extension=redis
    
    
    
    8、查看 phpinfo,确认扩展已经安装且启用。如图4
    查看 phpinfo,确认扩展已经安装且启用
    图4
    9、再次浏览首页,打印出获取到的缓存数据:”value”。如图5
    再次浏览首页,打印出获取到的缓存数据:"value"
    图5
    10、查看 Redis 中,配置的缓存数据库为 5。其中存在 key:laravel6_database_laravel6_cache:key,其值为:s:5:”value”;。符合预期。如图6
    查看 Redis 中,配置的缓存数据库为 5。其中存在 key:laravel6_database_laravel6_cache:key,其值为:s:5:"value";。符合预期
    图6
    11、为了避免与 Redis PHP 扩展本身发生类命名冲突,您需要从 app 配置文件的 aliases 数组中删除或重命名 Illuminate \ Support \ Facades \ Redis 外观别名。 通常,您应该完全删除此别名,并且仅在使用 Redis PHP 扩展时通过其完全限定的类名引用 Facade 。
    
    
    'RedisManager' => Illuminate\Support\Facades\Redis::class,
    
    
    
     
  • 在 Laravel 6 中,Blade 模板中的 组件 & 插槽 示例

    在 Laravel 6 中,Blade 模板中的 组件 & 插槽 示例

    1、参考网址:https://learnku.com/docs/laravel/6.x/blade/5147#20f1dd 。Blade 模板 – 组件 & 插槽 2、先编写一个可复用的「alert」组件,我们想在应用中复用它,新建文件:/resources/views/alert.blade.php
    <pre class="wp-block-syntaxhighlighter-code">
    
    <!-- /resources/views/alert.blade.php -->
    
    <div class="alert alert-danger">
        <div class="alert-title">{{ $title }}</div>
    
        {{ $slot }}
    </div>
    
    </pre>
    
    3、配置 /routes/web.php 中的路由
    
    
    Route::get('component', function () {
        return view('component');
    });
    
    
    
    4、新建模板文件:/resources/views/component.blade.php
    
    
    
    @component('alert')
        @slot('title')
            Forbidden
        @endslot
    
        You are not allowed to access this resource!
    @endcomponent
    
    
    
    
    5、打开网址:view-source:http://laravel-theme-demo.local/component 。查看源代码。符合预期。如图1
    打开网址:view-source:http://laravel-theme-demo.local/component 。查看源代码。符合预期
    图1
    <pre class="wp-block-syntaxhighlighter-code">
    
    
    <!-- /resources/views/alert.blade.php -->
    
    <div class="alert alert-danger">
        <div class="alert-title">Forbidden</div>
    
        You are not allowed to access this resource!
    </div>
    
    
    
    
    
    </pre>
    
     
  • 在 Laravel 6.20.43、Lighthouse 5.45.0 中,类 ‘ClearsSchemaCache’ 已弃用

    在 Laravel 6.20.43、Lighthouse 5.45.0 中,类 ‘ClearsSchemaCache’ 已弃用

    1、在 Laravel 6.20.43、Lighthouse 5.45.0 中,类 ‘ClearsSchemaCache’ 已弃用 。如图1
    在 Laravel 6.20.43、Lighthouse 5.45.0 中,类 'ClearsSchemaCache' 已弃用
    图1
    <pre class="wp-block-syntaxhighlighter-code">
    
    <?php
    
    namespace Modules\ThemeStore\Tests\Functional\GraphQl;
    
    use Nuwave\Lighthouse\Testing\MakesGraphQLRequests;
    use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
    use Nuwave\Lighthouse\Testing\ClearsSchemaCache;
    use Tests\CreatesApplication;
    
    class ThemeAssetGraphQlApiTest extends BaseTestCase
    {
        use CreatesApplication,
            ClearsSchemaCache,
            MakesGraphQLRequests;
    
        protected function setUp(): void
        {
            parent::setUp();
    
            $this->bootClearsSchemaCache();
        }
    }
    
    
    </pre>
    
    2、缘由应该在于 Lighthouse 的版本变化所导致。类 ‘ClearsSchemaCache’ 的作用为在运行任何测试之前先清除掉模式缓存。 3、参考:https://lighthouse-php.com/5/testing/phpunit.html#setup ,决定替换为 类 ‘RefreshesSchemaCache’ 4、编辑 /Modules/ThemeStore/Tests/Functional/GraphQl/ThemeAssetGraphQlApiTest.php。如图2
    编辑 /Modules/ThemeStore/Tests/Functional/GraphQl/ThemeAssetGraphQlApiTest.php
    图2
    <pre class="wp-block-syntaxhighlighter-code">
    
    <?php
    
    namespace Modules\ThemeStore\Tests\Functional\GraphQl;
    
    use Nuwave\Lighthouse\Testing\MakesGraphQLRequests;
    use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
    use Nuwave\Lighthouse\Testing\RefreshesSchemaCache;
    use Tests\CreatesApplication;
    
    class ThemeAssetGraphQlApiTest extends BaseTestCase
    {
        use CreatesApplication,
            ClearsSchemaCache,
            MakesGraphQLRequests;
    
        protected function setUp(): void
        {
            parent::setUp();
    
            $this->bootRefreshesSchemaCache();
        }
    }
    
    
    </pre>
    
    5、运行测试,测试通过。如图3
    运行测试,测试通过
    图3
    
    
    PS E:\wwwroot\object> .\vendor\bin\phpunit --process-isolation .\Modules\ThemeStore\Tests\Functional\GraphQl\ThemeAssetGraphQlApiTest.php
    PHPUnit 7.5.20 by Sebastian Bergmann and contributors.
    
    ...                                                                 3 / 3 (100%)
    
    Time: 7.73 seconds, Memory: 16.00 MB
    
    OK (3 tests, 11 assertions)
    PS E:\wwwroot\object>
    
    
    
  • 在 Laravel 6、Module、Lighthouse 中实现 安全 验证 的流程(使用 @rules 指令,使用 Exists 规则)

    在 Laravel 6、Module、Lighthouse 中实现 安全 验证 的流程(使用 @rules 指令,使用 Exists 规则)

    1、当请求响应成功时的结构。如图1
    当请求响应成功时的结构
    图1
    
    
    
    mutation {
      onlineStoreThemePreviewCodeGenerate(themeId: "vogue") {
        themePreviewCode
      }
    }
    
    
    
    
    
    
    {
      "data": {
        "onlineStoreThemePreviewCodeGenerate": {
          "themePreviewCode": "eyJpdiI6IjZlZ3RpZzlyZmp6S3BzQWJcL0N1NVR3PT0iLCJ2YWx1ZSI6IkNGdVwvdGJMZFI2MWJPRXFMbTNhdmVOUVVCVDhzb1ZnSzFNQzd2Y1RoSElGMmw4VkxOWFppbnlNbmtjaFNnbG9FXC9Oa1hYSndRU1hlcmpFMktneFNkQmVoMjhENnoxb3dQY0lxNHZnemJrNXlLTlpNKzJmbEU4RTFXNnFza2dyVG4iLCJtYWMiOiI0NzcwZjllYjIxZDliOGFkMTU2OTdiZmVmYWViN2I2OTI5NWE0ZDFjOTBmOGU1MGMyZjI3MzBjNTQxMWE3ODQ2In0="
        }
      }
    }
    
    
    
    2、但是,现阶段并未针对请求参数进行安全验证。参考:https://lighthouse-php.com/master/security/validation.html#single-arguments 。Lighthouse 允许您在查询和变更中使用 Laravel 的验证。 3、此 GraphQL API 的变更仅有一个请求参数,即 themeId,仅需要验证此字段是否在表中存在即可。 4、利用内置验证规则的最简单方法是使用 @rules 指令。使用 Exists 规则
    
    
    extend type Mutation {
        "生成主题预览代码"
        onlineStoreThemePreviewCodeGenerate(themeId: ID! @rules(apply: ["exists:theme_asset,theme_id"])): OnlineStoreThemePreviewCodeGeneratePayload @field(resolver: "Modules\\ThemeStore\\Resolver\\ThemePreview\\GenerateThemePreviewCodeResolver")
    }
    
    
    
    5、测试验证规则是否有效,确定有效。如图2
    测试验证规则是否有效,确定有效
    图2
    
    
    
    mutation {
      onlineStoreThemePreviewCodeGenerate(themeId: "vogue1") {
        themePreviewCode
      }
    }
    
    
    
    
    
    
    {
      "errors": [
        {
          "message": "Validation failed for the field [onlineStoreThemePreviewCodeGenerate].",
          "extensions": {
            "validation": {
              "themeId": [
                "The selected theme id is invalid."
              ]
            },
            "category": "validation"
          },
          "locations": [
            {
              "line": 2,
              "column": 3
            }
          ],
          "path": [
            "onlineStoreThemePreviewCodeGenerate"
          ],
          "trace": ...
        }
      ],
      "data": {
        "onlineStoreThemePreviewCodeGenerate": null
      }
    }
    
    
    
    6、查看 Laravel Telescope 中请求中的 SQL 语句。
    
    
    select
      count(*) as aggregate
    from
      `theme_asset`
    where
      `theme_id` = 'vogue1'
    
    
    
    7、但是,现阶段还存在一个问题,因为表名称的前缀恰好是 ”,如果设置为 ‘object_’,可能会有问题。再次请求,发现报错,符合预期。说明验证规则中会自动读取表前缀的。无需要调整。如图3
    但是,现阶段还存在一个问题,因为表名称的前缀恰好是 '',如果设置为 'object_',可能会有问题。再次请求,发现报错,符合预期。说明验证规则中会自动读取表前缀的。无需要调整
    图3
    
    
            'mysql' => [
                ...
                'prefix' => 'object_',
            ],
    
    
    
    
    
    {
      "errors": [
        {
          "debugMessage": "SQLSTATE[42S02]: Base table or view not found: 1146 Table 'object_store.object_theme_asset' doesn't exist (SQL: select count(*) as aggregate from `object_theme_asset` where `theme_id` = vogue1)",
          "message": "Internal server error",
          "extensions": {
            "category": "internal"
          },
          "locations": [
            {
              "line": 2,
              "column": 3
            }
          ],
          "path": [
            "onlineStoreThemePreviewCodeGenerate"
          ],
          "trace": [
            ...
          ]
        }
      ],
      "data": {
        "onlineStoreThemePreviewCodeGenerate": null
      }
    }
    
    
    
  • Key conedevelopment/blade-filters is a duplicate in ./composer.json at line 91。Warning: The lock file is not up to date with the latest changes in composer.json

    Key conedevelopment/blade-filters is a duplicate in ./composer.json at line 91。Warning: The lock file is not up to date with the latest changes in composer.json

    1、执行 composer install 时,报错:Class ‘Pine\BladeFilters\BladeFilters’ not found。如图1
    执行 composer install 时,报错:Class 'Pine\BladeFilters\BladeFilters' not found
    图1
    
    
    > Illuminate\Foundation\ComposerScripts::postAutoloadDump
    > @php artisan package:discover --ansi
    
       Symfony\Component\Debug\Exception\FatalThrowableError  : Class 'Pine\BladeFilters\BladeFilters' not found
    
      at E:\wwwroot\object\Modules\ThemeAssetCdn\View\ThemeAssetFilters.php:22
        18|     }
        19|
        20|     public static function scriptTag()
        21|     {
      > 22|         BladeFilters::macro('script_tag', function (string $asset,$type = 'text/javascript', $async = null, $defer = null) {
        23|             static $scripts = [];
        24|             if (isset($scripts[$asset])) {
        25|                 return '';
        26|             } else {
    
    
    
    
    2、编辑 composer.json,添加 “conedevelopment/blade-filters”: “^0.8”
    
    
        "require": {
            ...
            "conedevelopment/blade-filters": "^0.8"
        },
    
    
    
    3、再次执行时,提示:Key conedevelopment/blade-filters is a duplicate in ./composer.json at line 91。Warning: The lock file is not up to date with the latest changes in composer.json。如图2
    再次执行时,提示:Key conedevelopment/blade-filters is a duplicate in ./composer.json at line 91。Warning: The lock file is not up to date with the latest changes in composer.json
    图2
    <pre class="wp-block-syntaxhighlighter-code">
    
    PS E:\wwwroot\object> composer install
    Key conedevelopment/blade-filters is a duplicate in ./composer.json at line 91
    Installing dependencies from lock file (including require-dev)
    Verifying lock file contents can be installed on current platform.
    Warning: The lock file is not up to date with the latest changes in composer.json. You may be getting outdated dependencies. It is recommended that you run `composer update` or `composer update <package name>`.
    Nothing to install, update or remove
    
    </pre>
    
    4、参考 Warning,执行 composer update conedevelopment/blade-filters。如图3
    参考 Warning,执行 composer update conedevelopment/blade-filters
    图3
    
    
    PS E:\wwwroot\object> composer update conedevelopment/blade-filters
    Key conedevelopment/blade-filters is a duplicate in ./composer.json at line 91
    Loading composer repositories with package information
    Info from https://repo.packagist.org: #StandWithUkraine
    Updating dependencies
    Lock file operations: 23 installs, 0 updates, 1 removal
      - Removing neobject/facebook-conversions-api (1.4.0)
      - Locking barryvdh/laravel-debugbar (v3.6.7)
      - Locking conedevelopment/blade-filters (v0.8.0)
      - Locking elasticsearch/elasticsearch (8.x-dev 3cab97a)
      - Locking ezimuel/guzzlestreams (3.0.1)
      - Locking ezimuel/ringphp (1.2.0)
      - Locking haydenpierce/class-finder (0.4.3)
      - Locking laragraph/utils (v1.3.0)
      - Locking laravel/scout (v8.6.1)
      - Locking laravie/html (v6.0.1)
      - Locking lstrojny/functional-php (1.17.0)
      - Locking maximebf/debugbar (v1.18.0)
      - Locking nuwave/lighthouse (v5.45.0)
      - Locking orchestra/asset (v4.0.1)
      - Locking orchestra/contracts (v4.1.1)
      - Locking orchestra/support (v4.1.1)
      - Locking react/promise (v2.9.0)
      - Locking respect/stringifier (0.2.0)
      - Locking respect/validation (2.2.3)
      - Locking spatie/valuestore (1.3.0)
      - Locking statamic/stringy (3.1.2)
      - Locking tamayo/laravel-scout-elastic (8.0.3)
      - Locking thecodingmachine/safe (v1.3.3)
      - Locking webonyx/graphql-php (v14.11.5)
    Writing lock file
    Installing dependencies from lock file (including require-dev)
    Package operations: 23 installs, 0 updates, 1 removal
      - Downloading conedevelopment/blade-filters (v0.8.0)
      - Downloading elasticsearch/elasticsearch (8.x-dev 3cab97a)
      - Downloading lstrojny/functional-php (1.17.0)
      - Downloading nuwave/lighthouse (v5.45.0)
      - Downloading statamic/stringy (3.1.2)
      - Downloading orchestra/contracts (v4.1.1)
      - Downloading orchestra/support (v4.1.1)
      - Downloading laravie/html (v6.0.1)
      - Downloading orchestra/asset (v4.0.1)
      - Downloading spatie/valuestore (1.3.0)
      - Removing neobject/facebook-conversions-api (1.4.0)
      - Installing maximebf/debugbar (v1.18.0): Extracting archive
      - Installing barryvdh/laravel-debugbar (v3.6.7): Extracting archive
      - Installing conedevelopment/blade-filters (v0.8.0): Extracting archive
      - Installing react/promise (v2.9.0): Extracting archive
      - Installing ezimuel/guzzlestreams (3.0.1): Extracting archive
      - Installing ezimuel/ringphp (1.2.0): Extracting archive
      - Installing elasticsearch/elasticsearch (8.x-dev 3cab97a): Extracting archive
      - Installing lstrojny/functional-php (1.17.0): Extracting archive
      - Installing webonyx/graphql-php (v14.11.5): Extracting archive
      - Installing thecodingmachine/safe (v1.3.3): Extracting archive
      - Installing laragraph/utils (v1.3.0): Extracting archive
      - Installing haydenpierce/class-finder (0.4.3): Extracting archive
      - Installing nuwave/lighthouse (v5.45.0): Extracting archive
      - Installing statamic/stringy (3.1.2): Extracting archive
      - Installing orchestra/contracts (v4.1.1): Extracting archive
      - Installing orchestra/support (v4.1.1): Extracting archive
      - Installing laravie/html (v6.0.1): Extracting archive
      - Installing orchestra/asset (v4.0.1): Extracting archive
      - Installing respect/stringifier (0.2.0): Extracting archive
      - Installing respect/validation (2.2.3): Extracting archive
      - Installing spatie/valuestore (1.3.0): Extracting archive
      - Installing laravel/scout (v8.6.1): Extracting archive
      - Installing tamayo/laravel-scout-elastic (8.0.3): Extracting archive
    9 package suggestions were added by new dependencies, use `composer suggest` to see details.
    Package fzaninotto/faker is abandoned, you should avoid using it. No replacement was suggested.
    Package swiftmailer/swiftmailer is abandoned, you should avoid using it. Use symfony/mailer instead.
    Package moontoast/math is abandoned, you should avoid using it. Use brick/math instead.
    Package phpunit/php-token-stream is abandoned, you should avoid using it. No replacement was suggested.
    Generating optimized autoload files
    > Google\Task\Composer::cleanup
    Class Sofa\Eloquence\Searchable\Searchable located in E:/wwwroot/object/vendor/sofa/eloquence-base/src\Contracts\Searchable\Searchable.php does not comply with psr-4 autoloading standard. Skipping.
    Class Modules\ThemeStore\Tests\FactoryTest located in E:/wwwroot/object/Modules\ThemeStore\Tests\Unit\FactoryTest.php does not comply with psr-4 autoloading standard. Skipping.
    > Illuminate\Foundation\ComposerScripts::postAutoloadDump
    > @php artisan package:discover --ansi
    Discovered Package: arubacao/asset-cdn
    Discovered Package: axlon/laravel-postal-code-validation
    Discovered Package: barryvdh/laravel-debugbar
    Discovered Package: beyondcode/laravel-dump-server
    Discovered Package: beyondcode/laravel-er-diagram-generator
    Discovered Package: boaideas/laravel-cli-create-user
    Discovered Package: conedevelopment/blade-filters
    Discovered Package: cviebrock/eloquent-sluggable
    Discovered Package: dingo/api
    Discovered Package: fideloper/proxy
    Discovered Package: genealabs/laravel-model-caching
    Discovered Package: igaster/laravel-theme
    Discovered Package: ignited/laravel-omnipay
    Discovered Package: intervention/image
    Discovered Package: jenssegers/agent
    Discovered Package: jgrossi/corcel
    Discovered Package: laravel/passport
    Discovered Package: laravel/scout
    Discovered Package: laravel/socialite
    Discovered Package: laravel/tinker
    Discovered Package: laravel/ui
    Discovered Package: maatwebsite/excel
    Discovered Package: mavinoo/laravel-batch
    Discovered Package: nesbot/carbon
    Discovered Package: nunomaduro/collision
    Discovered Package: nuwave/lighthouse
    Discovered Package: nwidart/laravel-modules
    Discovered Package: orangehill/iseed
    Discovered Package: overtrue/laravel-pinyin
    Discovered Package: overtrue/laravel-wechat
    Discovered Package: prettus/l5-repository
    Discovered Package: s-ichikawa/laravel-sendgrid-driver
    Discovered Package: sentry/sentry-laravel
    Discovered Package: silber/page-cache
    Discovered Package: socialiteproviders/manager
    Discovered Package: sofa/eloquence-base
    Discovered Package: sofa/eloquence-mutable
    Discovered Package: spatie/laravel-activitylog
    Discovered Package: spatie/laravel-permission
    Discovered Package: spatie/laravel-query-builder
    Discovered Package: spatie/laravel-sitemap
    Discovered Package: tamayo/laravel-scout-elastic
    Discovered Package: torann/geoip
    Package manifest generated successfully.
    115 packages you are using are looking for funding.
    Use the `composer fund` command to find out more!
    
    
    
    5、再次执行 composer install 时,不再报错。
    
    
    PS E:\wwwroot\object> composer install
    Key conedevelopment/blade-filters is a duplicate in ./composer.json at line 91
    Installing dependencies from lock file (including require-dev)
    Verifying lock file contents can be installed on current platform.
    Nothing to install, update or remove
    Package fzaninotto/faker is abandoned, you should avoid using it. No replacement was suggested.
    Package swiftmailer/swiftmailer is abandoned, you should avoid using it. Use symfony/mailer instead.
    Package moontoast/math is abandoned, you should avoid using it. Use brick/math instead.
    Package phpunit/php-token-stream is abandoned, you should avoid using it. No replacement was suggested.
    Generating optimized autoload files
    > Google\Task\Composer::cleanup
    Class Sofa\Eloquence\Searchable\Searchable located in E:/wwwroot/object/vendor/sofa/eloquence-base/src\Contracts\Searchable\Searchable.php does not comply with psr-4 autoloading standard. Skipping.
    Class Modules\ThemeStore\Tests\FactoryTest located in E:/wwwroot/object/Modules\ThemeStore\Tests\Unit\FactoryTest.php does not comply with psr-4 autoloading standard. Skipping.
    > Illuminate\Foundation\ComposerScripts::postAutoloadDump
    > @php artisan package:discover --ansi
    Discovered Package: arubacao/asset-cdn
    Discovered Package: axlon/laravel-postal-code-validation
    Discovered Package: barryvdh/laravel-debugbar
    Discovered Package: beyondcode/laravel-dump-server
    Discovered Package: beyondcode/laravel-er-diagram-generator
    Discovered Package: boaideas/laravel-cli-create-user
    Discovered Package: conedevelopment/blade-filters
    Discovered Package: cviebrock/eloquent-sluggable
    Discovered Package: dingo/api
    Discovered Package: fideloper/proxy
    Discovered Package: genealabs/laravel-model-caching
    Discovered Package: igaster/laravel-theme
    Discovered Package: ignited/laravel-omnipay
    Discovered Package: intervention/image
    Discovered Package: jenssegers/agent
    Discovered Package: jgrossi/corcel
    Discovered Package: laravel/passport
    Discovered Package: laravel/scout
    Discovered Package: laravel/socialite
    Discovered Package: laravel/tinker
    Discovered Package: laravel/ui
    Discovered Package: maatwebsite/excel
    Discovered Package: mavinoo/laravel-batch
    Discovered Package: nesbot/carbon
    Discovered Package: nunomaduro/collision
    Discovered Package: nuwave/lighthouse
    Discovered Package: nwidart/laravel-modules
    Discovered Package: orangehill/iseed
    Discovered Package: overtrue/laravel-pinyin
    Discovered Package: overtrue/laravel-wechat
    Discovered Package: prettus/l5-repository
    Discovered Package: s-ichikawa/laravel-sendgrid-driver
    Discovered Package: sentry/sentry-laravel
    Discovered Package: silber/page-cache
    Discovered Package: socialiteproviders/manager
    Discovered Package: sofa/eloquence-base
    Discovered Package: sofa/eloquence-mutable
    Discovered Package: spatie/laravel-activitylog
    Discovered Package: spatie/laravel-permission
    Discovered Package: spatie/laravel-query-builder
    Discovered Package: spatie/laravel-sitemap
    Discovered Package: tamayo/laravel-scout-elastic
    Discovered Package: torann/geoip
    Package manifest generated successfully.
    115 packages you are using are looking for funding.
    Use the `composer fund` command to find out more!
    
    
    
  • 执行命令:npm run build 时,提示:npm ERR! Missing script: “build”

    执行命令:npm run build 时,提示:npm ERR! Missing script: “build”

    1、执行命令:npm run build 时,提示:npm ERR! Missing script: “build”。如图1
    执行命令:npm run build 时,提示:npm ERR! Missing script: "build"
    图1
    
    
    PS E:\wwwroot\object> npm run build
    npm ERR! Missing script: "build"
    npm ERR!
    npm ERR! To see a list of scripts, run:
    npm ERR!   npm run
    
    npm ERR! A complete log of this run can be found in:
    npm ERR!     C:\Users\Lenovo\AppData\Local\npm-cache\_logs\2022-04-15T01_30_16_068Z-debug.log
    
    
    
    2、查看 package.json 文件,可以确认 scripts 中并未包含 build 脚本。如图2
    查看 package.json 文件,可以确认 scripts 中并未包含 build 脚本
    图2
    
    
    {
      "private": true,
      "scripts": {
        "test": "jest",
        "dev": "npm run development",
        "development": "mix",
        "watch": "mix watch",
        "watch-poll": "mix watch -- --watch-options-poll=1000",
        "hot": "mix watch --hot",
        "production": "mix --production",
        "prod": "npm run production",
        "gh-pages": "gh-pages -d public/docs -r https://github.com/pheye/wdocs.git",
        "analyzer": "NODE_ENV=production npm_config_report=true npm run prod"
      },
      "devDependencies": {
        "@sentry/webpack-plugin": "^1.13.0",
        "babel-core": "^6.26.3",
        "babel-eslint": "^10.1.0",
        "babel-jest": "^25.1.0",
        "babel-plugin-component": "^1.1.1",
        "babel-plugin-import": "^1.13.0",
        "babel-preset-es2015": "^6.24.1",
        "credit-card-type": "^9.1.0",
        "cross-env": "^5.1",
        "eslint": "^6.8.0",
        "eslint-config-airbnb": "^18.1.0",
        "eslint-plugin-import": "^2.20.1",
        "eslint-plugin-jsx-a11y": "^6.2.3",
        "eslint-plugin-react": "^7.19.0",
        "gh-pages": "^3.2.3",
        "jest": "^25.1.0",
        "jest-allure": "^0.1.1",
        "jest-puppeteer": "^4.4.0",
        "laravel-mix": "^6.0.31",
        "laravel-mix-alias": "^1.0.3",
        "laravel-mix-bundle-analyzer": "^1.0.5",
        "laravel-mix-versionhash": "^2.0.1",
        "mockjs": "^1.1.0",
        "popper.js": "^1.12",
        "postcss": "8.3.1",
        "regenerator-runtime": "^0.13.3",
        "resolve-url-loader": "^2.3.1",
        "sass": "1.32.12",
        "sass-loader": "12.3.0",
        "sass-resources-loader": "^2.2.4",
        "slick-carousel": "^1.8.1",
        "terser-webpack-plugin": "5.2.4",
        "vue": "^2.5.17",
        "vue-custom-scrollbar": "^1.4.0",
        "vue-template-compiler": "^2.6.11"
      },
      "dependencies": {
        "@babel/plugin-proposal-nullish-coalescing-operator": "^7.16.5",
        "@babel/plugin-proposal-optional-chaining": "^7.16.5",
        "@sentry/browser": "^5.27.0",
        "@sentry/integrations": "^5.27.0",
        "@stripe/stripe-js": "^1.7.0",
        "axios": "^0.21.1",
        "babel-polyfill": "^6.26.0",
        "better-scroll": "^1.15.2",
        "bootstrap": "^4.6.1",
        "credit-card-type": "^9.1.0",
        "currency-symbol-map": "^4.0.4",
        "element-ui": "^2.13.0",
        "jquery": "^3.5",
        "lazysizes": "^5.2.0",
        "lodash": "^4.17.21",
        "normalize.css": "^8.0.1",
        "puppeteer": "^2.1.1",
        "qs": "^6.10.1",
        "slick-carousel": "^1.8.1",
        "uuid": "^7.0.3",
        "vue-awesome-swiper": "^3.1.3",
        "vue-country-flag": "^2.0.1",
        "vue-custom-scrollbar": "^1.4.0",
        "vue-i18n": "^8.22.2",
        "vue-loader": "15.9.8",
        "vue-phone-number-input": "^1.1.7",
        "vue-social-sharing": "^2.4.7",
        "vue-waterfall2": "^1.10.1",
        "vue-youtube": "^1.4.0",
        "vuex": "^3.1.2"
      }
    }
    
    
    
    
    3、根据提示:To see a list of scripts, run: npm run。要查看脚本列表,请运行 npm run。支持:npm run dev、npm run prod。如图3
    根据提示:To see a list of scripts, run: npm run。要查看脚本列表,请运行 npm run。支持:npm run dev、npm run prod
    图3
    
    
    PS E:\wwwroot\object> npm run
    Lifecycle scripts included in undefined:
      test
        jest
    
    available via `npm run-script`:
      dev
        npm run development
      development
        mix
      watch
        mix watch
      watch-poll
        mix watch -- --watch-options-poll=1000
      hot
        mix watch --hot
      production
        mix --production
      prod
        npm run production
      gh-pages
        gh-pages -d public/docs -r https://github.com/pheye/wdocs.git
      analyzer
        NODE_ENV=production npm_config_report=true npm run prod
    
    
    
    
    4、执行 npm run dev ,运行成功。如图4
    执行 npm run dev ,运行成功
    图4
    
    
    PS E:\wwwroot\object> npm run dev
    
    > dev
    > npm run development
    
    
    > development
    > mix
    
    
    ● Mix █████████████████████████ emitting (98%)
     after emit
    
    
    
    
    
       Laravel Mix v6.0.39
    
    
    &#x2714; Compiled Successfully in 127974ms
    
    
    
  • 在 Windows 10 中,内存占用持续超出 95% ,但是没有什么高内存占用的进程的分析排查(Heroku 占用了 4GB 的内存)

    在 Windows 10 中,内存占用持续超出 95% ,但是没有什么高内存占用的进程的分析排查(Heroku 占用了 4GB 的内存)

    1、在 Windows 10 中,内存占用持续超出 95% 。查看任务管理器,占用 98%。但是占用内存最大的 2 个进程加起来也不过 2GB。而内存总大小为 16GB。其他的进程占用内存都不大,理论上来说不至于占用比例这般地高了。如图1
    在 Windows 10 中,内存占用持续超出 95% 。查看任务管理器,占用 98%。但是占用内存最大的 2 个进程加起来也不过 2GB。而内存总大小为 16GB。其他的进程占用内存都不大,理论上来说不至于占用比例这般地高了
    图1
    2、查看性能 – 内存,使用中(已压缩):15.5GB。已提交:25BG/32.7GB。如图2
    查看性能 - 内存,使用中(已压缩):15.5GB。已提交:25BG/32.7GB
    图2
    3、打开360安全卫士 – 优化加速界面,基本上将所有待优化项全部优化后。仍然占用超过 95%。如图3
    打开360安全卫士 - 优化加速界面,基本上将所有待优化项全部优化后。仍然占用超过 95%
    图3
    4、重启电脑后,发现任务栏图标排列未垂直居中。但是内存占用仍然高达 25% 左右。打开360安全卫士 – 优化加速界面 – 优化记录 – 任务栏使用小图标 – 恢复默认。如图4
    重启电脑后,发现任务栏图标排列未垂直居中。但是内存占用仍然高达 25% 左右。打开360安全卫士 - 优化加速界面 - 优化记录 - 任务栏使用小图标 - 恢复默认
    图4
    5、一般习惯于每周一开机,然后持续至周五或者周六关机,一般来说,到周四的时候,内存占用基本上达到 95% 左右。如图5
    一般习惯于每周一开机,然后持续至周五或者周六关机,一般来说,到周四的时候,内存占用基本上达到 95% 左右
    图5
    6、当使用360安全卫士 – 我的电脑 – 立即体检 – 一键修复后,内存占用降低至:50% 左右。查看任务管理器,发现主要是 PhpStorm 的内存占用下降明显。从之前的 3200 MB 左右下降至 900 MB 左右。如图6
    当使用360安全卫士 - 我的电脑 - 立即体检 - 一键修复后,内存占用降低至:50% 左右。查看任务管理器,发现主要是 PhpStorm 的内存占用下降明显。从之前的 3200 MB 左右下降至 900 MB 左右
    图6
    7、但是,基于上间隔不到半天,PhpStorm 的内存占用就基本上又恢复至 3GB 左右。但是 IDE 占用 3GB 也不是不可以接受的。主要在于还有 10 余 GB 的内存,无法确定怎么也被占用得差不多了的。 8、参考:https://answers.microsoft.com/en-us/windows/forum/all/windows-10-upgrade-from-81-99-ram-usage-and/269be2e2-de0f-4e7a-b4fc-cc6dd40da2ca ,Network Diagnostic Usage (Windows 网络数据使用监视器) 简称 NDU 。按 win + R 打开运行,然后输入 regedit,进入注册表编辑页面,依次浏览到下面的选项上。在右侧的 Start 那项上双击,在弹出来的对话框中将数值设为 4,默认是 2,该设置禁用了 ndu 的某些部分。重启电脑,然后观察一下内存、CPU、硬盘等的占用情况有无改善。如图7
    Network Diagnostic Usage (Windows 网络数据使用监视器) 简称 NDU
    图7
    
    
    HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Services\Ndu
    
    
    
    9、参考:https://answers.microsoft.com/zh-hans/windows/forum/all/win10%E5%86%85%E5%AD%98%E5%8D%A0%E7%94%A8%E8%B6%85/23f4ac65-a125-4012-b541-d15f5f6e7051 。步骤2的时候,非分页缓冲池:1.2 GB。周四的时候,非分页缓冲池:516 MB。如图8
    参考:https://answers.microsoft.com/zh-hans/windows/forum/all/win10%E5%86%85%E5%AD%98%E5%8D%A0%E7%94%A8%E8%B6%85/23f4ac65-a125-4012-b541-d15f5f6e7051 。步骤2的时候,非分页缓冲池:1.2 GB。周四的时候,非分页缓冲池:516 MB
    图8
    10、一般非页面缓冲池越用越高都是一些软件出现了内存泄漏引起的。建议先卸载掉一些不常用的软件。然后再尝试卸载掉有可能导致内存泄漏的软件。最终卸载了软件:heroku,重启电脑后,内存占用降低至 70% 左右。说明 heroku 基本上占用了 4GB 左右的内存(占比 25%)。参考:https://www.shuijingwanwq.com/2021/12/29/5622/ 11、从周一开机至周五,持续运行了 5 天时间,一般每天晚上下班前会处于睡眠状态。现在的内存占用到周五的时候仍然基本上稳定在 85% 左右。相对于图1,PhpStorm 与 Google Chrome 占用的内存相对增加了 3GB 左右 。如图9
    从周一开机至周五,持续运行了 5 天时间,一般每天晚上下班前会处于睡眠状态。现在的内存占用到周五的时候仍然基本上稳定在 85% 左右。相对于图1,PhpStorm 与 Google Chrome 占用的内存相对增加了 3GB 左右
    图9