We are moving our forum in GitHub Discussions. For questions about Phalcon v3/v4 you can visit here and for Phalcon v5 here.

How can Phalcon create user defined common function?

I'm a beginner and I would like to know how can phalcon create user defined common function like getCurrentDateTime()?


Your question is ambiguous. Can you elaborate ?

In the other PHP Frame like codeigniter, it will have library or helper. I can define my own functions by using library and helper. For instance, I can create a user function named generate_code(). I can use my function all over the application. If I want to modify the business logic of code generatioin, I just need to change one function. I am the beginner of Phalcon and I cannot find this kind of support. Could you please guide me? Thanks.

edited May '14


You can use the DI container to store your class and then use it from wherever you want in your application. So for instance let's say that you have this class:

class Utils
    public function translate($string) {...}
    public function encode($string) {...}
    public function decode($string) {...}

in your bootstrap you will register this as a service

    function () { 
        return new Utils();

Then from any controller you can do then:

$newValue = $this->utils->translate($oldValue);

If you need to access the service in models you can use the

$utils = \Phalcon\Di::getDefault()->get('utils');

Thank you for your suggestion. And because I will create a Micro project, how can I use this class in /public/index.php?

edited May '14

Where I should put the Class?

any solutions?!

edited May '14

@EleRam, you are probably not very familliar with PHP ? You can put the class wherever you want, and then register its namespace. This is all. Example:

$loader = new \Phalcon\Loader();

    'Your\Class\Namespace'        => '/path/to/class.php',

edited May '14

@calinrada I'm not familiar with Phalcon. this is my first experience in frameworks.

Thank you :)