使用 composer 安装后包括 Swiftmailer 文件在内的问题

Troubles including Swiftmailer file after installation with composer

我是使用 composer 的新手,安装后在我的 public php 页面中包含 Swiftmailer 文件时遇到了一些问题。 我使用此指令使用 composer 安装了 Swiftmailer:

php composer.phar require swiftmailer/swiftmailer @stable

一切正常,文件安装在

./vendor/swiftmailer/swiftmailer/

由于文件在根目录中而不是在 public_html 中,我无法包含它们以开始使用它。

我在那个位置安装 Swiftmailer 是不是搞错了? 我需要改变它吗? 如果可以,有什么快速的方法吗?

如果你想使用由 Composer 安装的东西,你必须在你的代码中包含自动加载器。

并且因为包含 PHP 代码使用的是文件系统,而不是 Web 服务器访问权限,所以就能够通过 Web 服务器访问脚本而言,脚本位于何处并不重要 - 这是一件好事,因为您不希望通过网络访问每个 PHP 脚本。

您必须在脚本的第一行中包含 Composer 自动加载器,然后才能使用随 Composer 安装的所有内容。

include 'vendor/autoload.php'; // adjust the path depending on where your script is located.

这可能会导致这样的结果:

./public_html/index.php:

include '../vendor/autoload.php'; // located in  ./vendor/

$mailer = new \Swift_Mailer();

简而言之:在您的应用程序 bootstrap 中添加以下行 require 'vendor/autoload.php';(除非它已经存在)。

您只需包含此文件即可免费自动加载。 引用:https://getcomposer.org/doc/01-basic-usage.md#autoloading


长版:

Swiftermailer 将 lib/swift_required.php 文件添加到 Composer Autoloader:

https://github.com/swiftmailer/swiftmailer/blob/master/composer.json#L25

此文件需要一些其他 Swiftmailer 文件并注册 Swiftmailer Autoloader。

执行流程应该是这样的:

  • 你的申请index.php
  • 你的bootstrap.php
  • 需要 Composer 自动加载器
  • 每个请求都会加载 autoload 部分中的文件,例如 swiftmailer_required.php
  • 现在您可以使用$mailer = new \Swift_Mailer();