CakePHP:无法从自定义包加载类

2021-12-21 00:00:00 php cakephp cakephp-2.0

我们想在我们的一个控制器中使用 FPDF 库.

We want to use the FPDF library in one of our controllers.

我们创建了以下文件:

app
-Lib
--Fpdf
---files.php
---fpdf.php
---fdpf_wrapper.php <-- this is our class (FdpfWrapper) which extends the base FPDF class

就在控制器类之前,我们试试这个:

Right before the controller class, we try this:

App::uses('FpdfWrapper', 'Lib/Fpdf');

但每次都失败.我们做错了什么?

But it fails every time. What are we doing wrong?

推荐答案

首先,必须注册包路径才能与 App::usesLib/Fpdf没有这样的,默认只注册核心包.

First of all, package paths must be registered in order to be used with App::uses, and Lib/Fpdf is no such one, by default only the core packages are registered.

您可以扩展现有包的路径,在您的情况下为 Lib:

You could either extend the paths for an already existing package, in your case that would be Lib:

App::build(array('Lib' => array(APP . 'Lib' . DS . 'Fpdf' . DS)));

然后使用 App::uses('FpdfWrapper', 'Lib');

http://book.cakephp.org/2.0/en/core-utility-libraries/app.html#adding-paths-for-app-to-find-packages-in

或者更好地添加一个新包:

or better add a new package:

App::build(array('Lib/Fpdf' => array(APP . 'Lib' . DS . 'Fpdf' . DS)), App::REGISTER);

http://book.cakephp.org/2.0/en/core-utility-libraries/app.html#add-new-packages-to-an-application

然后你可以使用 App::uses('FpdfWrapper', 'Lib/Fpdf');

最后但并非最不重要的一点,当然文件名必须遵循@Nunser 已经提到的 CakePHP 约定,即 fdpf_wrapper.php 必须重命名为 FdpfWrapper.php

And last but not least, of course the filename must follow the CakePHP conventions as already mentioned by @Nunser, ie fdpf_wrapper.php must be renamed to FdpfWrapper.php

相关文章