Floris
Floris

Reputation: 3127

Zf2 Loading a custom class in project

I'm new to the Zend Framework. I added a bunch of API classes for Google Calendar to the /vendor/ folder. Then I wrote a custom class for authenticating and adding an event to my Google Calendar account. And placed it in /module/Application/src/Application/Util/GoogleAgenda.php

So. Now in the EventController (in module/Event/src/Event/EventController.php) I would like to use the custom GoogleAgenda class with something like this:

    $agenda = new \GoogleAgenda();
    if($agenda->auth()) {
        $success = $agenda->addEvent($event->serviceName, "", $event->locationName, "2014-02-27T17:00:00.000+00:00", "2014-02-27T18:00:00.000+00:00");
        if(!$success) {
            die("Google Calendar Api - Failed to add event");
        }
    }

This gives the error:

Fatal error: Class 'GoogleAgenda' not found in EventController.php on line 60

So, where to put my custom GoogleAgenda class? And how to load them from a controller class in another module.

I thought my Util folder was a good place to store this class. Because it is a util class that I would like to use in the entire application.

Upvotes: 1

Views: 489

Answers (1)

Tim Fountain
Tim Fountain

Reputation: 33148

You need the class to be autoloaded. Since you've put it in your application module, It's easiest for you that module's namespace and autoloader setup. Since the class lives at module/Application/src/Application/Util/GoogleAgenda.php, it's declaration should look like this:

<?php

namespace Application\Util;

class GoogleAgenda
{
    [...]
}

and usage for it would be:

$agenda = new \Application\Util\GoogleAgenda();

or, a little nicer:

use Application\Util\GoogleAgenda;

[...]

$agenda = new GoogleAgenda();

And how to load them from a controller class in another module

The code above should work from any module in your app.

Upvotes: 3

Related Questions