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

Phalcon Component Catch 22

Hello,

I am implementing DRY (Don't repeat yourself) as much as possible, which is why I have made seperate functions from repetitive tasks in my Controllers.

To create a "home" for these methods, I have created some Components classes, that each extend \Phalcon\Mvc\User\Component.

I can either:

  1. Call these component methods statically from the Controllers, using ComponentName::methodname(), provided I have declared the method as static in the Component of course... or:

  2. Make those Component methods non-static and instantiate the Component class first, before calling its methods. So like this: $test = new ComponentName; $result = $test->methodname();

The first option has my preference, but then I run into not being able to use the db connection from the Dependency Injector. Which I would call by using $this->di->get('db'); It doesn't work of course, because we cannot use $this without an object context.

Is there no easy way around this? Otherwise I have to go for method 2 and refactor much of my code?

I know this is probably more OO related stuff, but it stops me in embracing Phalcon to the fullest, which is why I post this question here.

Thanks! Alex



7.9k
Accepted
answer
edited Nov '14

you can use late static binding https://php.net/manual/en/language.oop5.late-static-bindings.php

here is an example of mine

class AuthBasic extends Component implements AuthInterface
{

    public function auth()
    {
       // Code here
    }

    public static function get()
    {
        return new self();
    }
}

you can access it with

AuthBasic::get()->auth();

You also can access DI via static way $di = Phalcon\DI::getDefault()



5.7k

Thanks so much! I have now used :

$connection = Phalcon\DI::getDefault()->get('db');

within the static method and it works!

Only question now is, do I have to repeat that declaration in every single static method I am configuring? Or could I do it in some sort of base Component class, that the current Component class extends.

Here I am somewhat at a loss, because I suppose when the method is called statically, this declaration is not done, because none of the class properties or instantiated.

I am probably overlooking something really basic and would appreciate any help. Best, Alex



7.9k

Yes you have repeat such declaration in each method but dont worry DI it self is singleton it will reuse DI object instead create new one.



5.7k

Ok clear, thanks again and have a great day, Alex