1

I thought autoloading was build into Zend so that if you tried to instantiate a class it would use the class name to try and find where the class's file was located.

I want to be able to load a DTO directory in my application's root directory using autoloader. I thought I could do something like this Application_DTO_MyClass for the file /application/dtos/myClass.php

I've tried googling it but haven't found anything useful. Any tips on the best way to do this?

Walt
  • 1,521
  • 2
  • 13
  • 29

1 Answers1

1

There are a couple of options open to you here depending on whether you want to create models in a subdirectory of Application/Models or create them in your own 'namespace' as a subdirectory of library. I am assuming you are using the recommended directory structure for Zend Framework.

For creating models in a sub directory of Application/Models, first create your directory; in your case Application/Models/Dto would be my recommendation.

In that directory create Myclass.php that would contain:-

class Application_Model_Dto_Myclass
{
    public function __construct()
    {
        //class stuff
    }
}

Which you would instantiate thus:-

$myObject = new Application_Model_Dto_Myclass();

If you want to create your classes in your own 'namespace' as a subdirectory of library then first create the directory library/Dto and, again create the file Myclass.php, which would look like this:-

class Dto_Myclass
{
    public function __construct()
    {
        //class stuff
    }
}

You will have to register this 'namespace'; I would recommend doing that in your application.ini by adding the line:

autoloadernamespaces[] = "Dto_"

You would instantiate this class thus:-

$myObject = new Dto_Myclass();

I'm not sure why you couldn't find this out through google, but you will find all this and more in the Zend Framework Programmers' Reference Guide. I also find the ZF code to be an excellent resource for working out how it all works.

vascowhite
  • 18,120
  • 9
  • 61
  • 77
  • Why would you call it using `new Application_Model_Myclass();` and not `new Application_Model_Dto_Myclass();` which is the actual class name? I see what you recommended works just doesn't make sense. What if you had a class in that DTO directory with the same ending? – Walt Mar 16 '12 at 23:18
  • Strange thing is it worked with the typo but without it, it still says it couldn't find the class. – Walt Mar 17 '12 at 01:50
  • Got it working. What you said is right I just had something incorrect in my code. Thanks again! – Walt Mar 17 '12 at 02:05