我正在尝试添加一个自定义用户代理,用于解析自定义移动应用程序用户代理以及现有的解析器。我试着关注这里的问题:https://github.com/matomo-org/device-detector/issues/5931但不能正确地做到这一点。
目录结构
UAParserService
|
|_ composer.json
|_ Vendor
|_ index.php
|_ custom_apps.yml
|_ CustomAppParser.php
|_ DeviceDetector.php
index.php <?php
require_once "vendor/autoload.php";
use DeviceDetector\DeviceDetector;
use DeviceDetector\Parser\Client\CustomAppParser;
$userAgent = "MyApp/1.0.0 (Linux; Android 9; ONEPLUS A6010)"; // Android App
$dd = new DeviceDetector($userAgent);
$parser = new CustomAppParser();
$dd -> addClientParser($parser);
$dd -> parse();
// Check if user agent is a bot
$isBot = $dd -> isBot();
if($isBot) {
echo json_encode(["is_bot" => $isBot]);
}
else {
$clientInfo = $dd->getClient();
$osInfo = $dd->getOs();
$device = $dd->getDeviceName();
$brand = $dd->getBrandName();
$model = $dd->getModel();
echo json_encode([
"is_bot" => $isBot,
"client_info" => $clientInfo,
"os_info" => $osInfo,
"device_type" => $device,
"device_brand" => $brand,
"device_model" => $model,
], JSON_PRETTY_PRINT);
}
DeviceDetector.php <?php
namespace UAParserService\DeviceDetector;
use function array_pop;
use function array_unshift;
class DeviceDetector extends \DeviceDetector\DeviceDetector
{
public function addClientParser($parser){
parent::addClientParser($parser);
$item = array_pop($this -> clientParsers);
array_unshift($this -> clientParsers, $item);
}
}
CustomAppParser.php <?php
namespace DeviceDetector\Parser\Client;
class CustomAppParser extends ClientParserAbstract
{
protected $fixtureFile = "custom_apps.yml";
protected $parserName = "mobile app";
protected function getRegexesDirectory()
{
return dirname(__DIR__);
}
}
composer.json {
"require": {
"piwik/device-detector": "3.11.7",
"ext-json": "*"
}
}
我对命名空间非常不友好,所以我可能做错了。我也确实遇到了一些错误:
( ! ) Fatal error: Uncaught Error: Class 'DeviceDetector\Parser\Client\FurryAppParser' not found in F:\web projects\project1\UAParserService\index.php on line 17
( ! ) Error: Class 'DeviceDetector\Parser\Client\CustomAppParser' not found in F:\web projects\project1\UAParserService\index.php on line 17
最佳答案
首先,您应该考虑将自己的类放入专用文件夹中,例如src
.
之后你可以添加
"autoload": {
"psr-4": {
"UAParserService\\": "src/"
}
}
给您的
composer.json
并使用 composer dump-autoload
更新自动加载器命令。此时,您将设置使用您的命名空间。
注意事项 :
src
中的所有类(class)文件夹必须以 UAParserService\
开始其命名空间UAParserService
在为您的类(class)搜索文件夹时,元素将被删除 例如,如果
DeviceDetector
类有namespace UAParserService\DeviceDetector;
它必须放入scr/DeviceDetector/DeviceDetector.php
文件。 CustomAppParser
也是如此类(class)。另外,如果你想使用 您自己的
DeviceDetector
在 index.php
你应该更新 use
致 use UAParserService\DeviceDetector\DeviceDetector;
的声明旁注 : 请不要在
->
周围使用空格方法调用的运算符;)。至少要么到处使用它,要么根本不使用它......附言 :请考虑重命名您的问题以反射(reflect)它解决的实际问题;)。我的意思是我们在这里解决命名空间问题,而不是扩展问题。
关于php - 扩展 matomo/piwik 设备检测器类以添加新的客户端解析器(命名空间问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56539720/