在 Prestashop 模块的一个文件中要求自动加载的方法?

2022-01-21 00:00:00 php composer-php prestashop autoload

我正在尝试将一组库与 Composer 一起用于 Prestashop 模块.

I'm trying to use a set of libraries with Composer for a Prestashop module.

我目前的方法是在每个文件中包含 vendor/autoload.php 文件(mymodule.phpcontrollers/front/foo.phpcontrollers/admin/bar.php 等)

My current approach is to include the vendor/autoload.php file on every file (mymodule.php, controllers/front/foo.php, controllers/admin/bar.php, etc.)

仅在 mymodule.php 之上执行 require 不是解决方案,我没有看到任何钩子来完成任务.

Doing the require only on top of the mymodule.php is not a solution, I don't see any hook to do the task.

有没有比copy & 更好的方法?将相同的代码段粘贴到每个 PHP 文件的顶部?谢谢!

Is there a better approach than copy & paste the same snippet on top of every PHP file? Thank you!

推荐答案

我已经找到方法了!

actionDispatcher 钩子适用于模型、钩子,但不适用于控制器.

The actionDispatcher hook was working for me with models, hooks, but not with controllers.

似乎有一个名为 moduleRoutes 的未记录的钩子会在 任何控制器之前加载.

Seems like there is a not documented hook called moduleRoutes which loads before any controller.

所以我已经能够以这种方式自动加载我所有模块的类:

So I've been able to autoload in all my module's classes this way:

<?php

if (!defined('_PS_VERSION_'))
    exit;

//_PS_MODULE_DIR_

require_once __DIR__.'/vendor/autoload.php'; // Autoload here for the module definition

class MyCustomModule extends DevnixPrestablocksModule { // My custom Prestashop framework (in experimental phase, https://github.com/devnix/prestablocks)

  // ...

  public function install() {
    return
      parent::install() &&
      $this->registerHook('moduleRoutes'); // Register the hook
  }


  public function hookModuleRoutes() {
    require_once __DIR__.'/vendor/autoload.php'; // And the autoload here to make our Composer classes available everywhere!
  }

相关文章