14

I have a class Called MyClass. It lives in app/Lib/MyDir/MyClass. I'd like to use App:uses() to load it, but can't get it to work.

In CakePHP 1.3 I would load it via:

App::import('Lib', 'MyDir/MyClass');  //this still works in CakePHP 2.1

In CakePHP 2.1 I'm trying to do:

App::uses('MyClass', 'Lib/MyDir');

When I try to 'new' up MyClass I get Class 'MyClass' not found.

Is it not possible to use App::uses on custom Lib classes? I can't continue to use App::import() because if 'App::import('Lib', 'MyDir/MyClass');' appears 2x in the code path I get a 'Cannot redeclare class' error in lib/Cake/Core/App.php on line 531

what am I doing wrong?

Edit: so if I do App::uses('MyClass', 'MyDir'); it works. Not sure if thats how its supposed to behaive, but reporting bug.

rynop
  • 41,200
  • 23
  • 87
  • 99
  • I found the following commit that should fix the problem (will make it so my usage above works). Once it makes it into a release I'll update this question. https://github.com/cakephp/cakephp/commit/8ed4876830546593f20db6c7e9aed299aa76a80a – rynop Feb 09 '12 at 00:59
  • **whoever googles this** make sure the file contains a class with the same name. [more info in this answer](http://stackoverflow.com/questions/19120409/cakephp-unable-to-load-class-from-app-lib/37231878#37231878) – aexl May 14 '16 at 21:08

1 Answers1

20

did you try

App::uses('MyClass', 'MyDir');

? since "Lib" itself can be seen as a base directory

PS: you are even supposed to group everything inside Lib in subfolders (packages) similar to the core.

mark
  • 21,478
  • 3
  • 46
  • 67
  • Yes this works. But that does not seem intuitive. http://book.cakephp.org/2.0/en/core-utility-libraries/app.html#App::uses even has an example for 'Lib'. Yep i'm trying to put everything in sub-folders. Lets say I didnt have a class in the Lib dir in a subfolder (it was just in app/Lib/MyClass.php) - would i not be able to load it with ::uses()? – rynop Feb 08 '12 at 23:15
  • yes, you are. it is than just App::uses('MyClass', 'Lib'); but should be avoided :) – mark Feb 09 '12 at 09:44
  • I am working in version cakephp 2.5.4. I need to import one Lib class in another Lib class. for ex : I have a class Search.php under Lib folder,and GooglePlus.php under Lib/Google folder. I need to use GooglePlus.php file in Search.php, but its not working. I tried app:build function too described in http://book.cakephp.org/2.0/en/core-utility-libraries/app.html to register the Lib class. How do i use one lib class in another ? or if its not possible , what is alternate approach for this ? – Dashrath Dec 19 '14 at 09:44
  • It is possible, exactly the way I described above: Always use App::uses() for all classes you use at the top of each file and it will work just fine. – mark Dec 19 '14 at 10:20