在 Prestashop 1.7.5 中创建和访问自定义模块的 REST 路由

Creating and accessing custom module's REST routes in Prestashop 1.7.5

我正在尝试在我的 Prestashop 1.7.5 模块中创建自定义控制器。

我创建了一个自定义控制器:

# /var/www/html/modules/Profit/src/controller/ProductProfitController.php

namespace Profit\Controller;

use PrestaShopBundle\Controller\Admin\FrameworkBundleAdminController;
use Symfony\Component\HttpFoundation\JsonResponse;

class ProductProfitController extends FrameworkBundleAdminController {

    public function test() {
        return JsonResponse();
    }
}

我用 composer.json 文件加载了 class:

# /var/www/html/modules/Profit/composer.json

{
    "name": "company/profit",
    "description": "Moduł opłacalności",
    "authors": [
        {
            "name": "Name",
            "email": "Email"
        }
    ],
    "require": {
        "php": ">=5.6.0"
    },
    "autoload": {
        "psr-4": {            
            "Profit\Controller\": "src/controller/"
        },
        "classmap": [
            "Profit.php",
            "src/"
        ],
        "exclude-from-classmap": []
    },
    "config": {
        "preferred-install": "dist",
        "prepend-autoloader": false
    },
    "type": "prestashop-module",
    "author": "Name",
    "license": ""
}

我在模块的 routes 文件夹中添加了一个路由

# /var/www/html/modules/Profit/config/routes.yml

update_price_cut:
    path: Profit/price-cut
    methods: [GET]
    defaults:
      _controller: 'Profit\Controller\ProductProfitController::test'

但我不知道如何访问该路由。我试过了:

localhost:8001/admin-dev/Profit/price-cut
localhost:8001/modules/Profit/price-cut
localhost:8001/modules/Profit/Profit/price-cut
localhost:8001/Profit/price-cut

None 这些作品。它们中的每一个都会导致 404 错误。

这是创建模块自定义控制器路由的正确方法吗?我该如何解决这个问题?

注意: 这个控制器应该是一个 BackOffice 控制器。我想用它来更新默认 PrestaShop 产品列表中的产品详细信息。

在管理控制器中尝试 $this->generateUrl('update_price_cut')。它将生成到您的控制器的正确路径。或者,如果您在不同的地方需要它,您可以创建自己的服务并使用它。您可以找到更多信息 here

现有的答案对我帮助不大,而且它没有提到实际的 URL,因为人们通过 Google.

来到这里

设置

# /config/routes.yml

my_route_name:
  path: /my_project/my_path # Leading / can be omitted
  methods: [GET]
  defaults:
    _controller: 'Me\MyProject\Admin\Controllers\MyController::indexAction' # This can point to any class and any public method.
// my_project/admin/controllers/MyController.php

class MyController extends FrameworkBundleAdminController
{
    public function indexAction(): string 
    {
        return 'hello';
    }
}

然后我又走上了同样的路,试图找出 URL,最后我到了这里。

实际控制人URL

另一个答案中提到的方法 generateUrl 由于某种原因在我的任何管理控制器中都不存在。我看了看,发现它是在 Symfony 特征中定义的。它基本上是这样做的:

$this->container->get('router')->generate('my_route_name', [], UrlGeneratorInterface::ABSOLUTE_PATH);

最终返回了工作 URL:

/admin1/index.php/modules/my_project/my_path?_token=...

希望这对其他人有帮助。