We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Registering Class automatically

Hi guys,

I need a confirmation if what i'm doing isn't redundant.

public/index


    $loader = new \Phalcon\Loader();
    $loader->registerDirs(array(
        '../app/controllers/',
        '../app/models/'
    ))->register();

    /**
     * Register a user component
     */
    $di->set('client', function(){
        return new ClientController();
    });

app/view/client/index.php calling html function

    <?php echo $this->getContent(); ?>
    <?php echo $this->client->doHtml(); ?>

This is working, but I really need to register the class? The registerDirs method doesn't do this automatically? Perhaps is there any way to do this happen automatically?

Controllers doesn't have to be registered as a custom Class. Phalcon does this automaticly for you.

Custom classes need to be registered in the service.php if they are not a Controller or Model or sth. like that.

So at the end you can remove this line of code and your app should work too.

    /**
     * Register a user component
     */
    $di->set('client', function(){
        return new ClientController();
    });


125.8k
Accepted
answer

The autoloader makes your class available. Registering the directory the classfile is in will suffice to make the class available. However, the second part, the "Register a user component" part, is putting a new instance of that class inside the Dependancy Injector. This makes it available in your view as $this->client. This second part isn't necessary, but it is pretty convenient. You could, for instance, not "register" the class, then just do this in your view.

<?php $Client = new ClientController();
$Client->doHTML();
?>

I think we can all agree though, that using the Dependancy Injector is much easier and reduces code duplication.



1.5k
edited Sep '14

Thank you for both responses. I'm familiarizing myself with phalcon yet and sometimes I'm unsure if I'm doing the right way