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

register new services

I have a forder libararys in forder app. I have a file Myvalidate.php in forder librarys.

use Phalcon\Validation;
use Phalcon\Validation\Validator\Email;
use Phalcon\Validation\Validator\PresenceOf;
class Myvalidate extends Validation
{

    public function initialize()
    {
        $this->add(
            'username',
            new PresenceOf(
                array(
                    'message' => 'The user name is required'
                )
            )
        );

        $this->add(
            'email',
            new PresenceOf(
                array(
                    'message' => 'The e-mail is required'
                )
            )
        );

        $this->add(
            'email',
            new Email(
                array(
                    'message' => 'The e-mail is not valid'
                )
            )
        );
        $this->add(
            'password',
            new Email(
                array(
                    'message' => 'The password is required'
                )
            )
        );

    }
}
```php

and file index.php in public/index.php

```php
$di->set('myvalidation', function () {
     require __DIR__.'/../app/librarys/Myvalidation.php';
     return $mycheck;
    });

and in UserController I use $validation = $di->get("mycheck"); but get error service "mycheck" not found in service container. Please help me..

edited Mar '16

Yes it's not found, you set it as myvalidation and you access mycheck in controller.

sorry, If I use myvalidation and access myvalidation in UserController I use $validation = $di->get("myvalidation"); but get error service "myvalidation" not found in service container. Please help me... Please help me. this is https://stackoverflow.com/questions/24315909/how-to-create-a-new-injectable-service-in-phalcon tutorial class JsonService It run good. But I want to move class JsonService to file app/librarys/JsonService .php same with problem above.Please help me

edited Mar '16

But tell me what you are doing ? You are not creating new object of any class in serive defintion. You are returning nothing from service.

Example class JsonService { public function getJson($url, $assoc=false) { $curl = curl_init($url); $json = curl_exec($curl); curl_close($curl); return json_decode($json, $assoc); } }

$di = new Phalcon\DI();

//Register a "db" service in the container $di->setShared('db', function() { return new Connection(array( "host" => "localhost", "username" => "root", "password" => "secret", "dbname" => "invo" )); });

//Register a "filter" service in the container $di->setShared('filter', function() { return new Filter(); });

// Your json service... $di->setShared('jsonService', function() { return new JsonService(); });

// Then later in the app... DI::getDefault()->getShared('jsonService')->getJson(…);

// Or if the class where you're accessing the DI extends Phalcon\DI\Injectable $this->di->getShared('jsonService')->getJson(…); But I want move class JsonService to file in folder app/librarys/JsonService.php and then I use $this->di->getShared('jsonService')->getJson(…); in any Controller

edited Mar '16

Yes its working beacause you are returning new object. In your example you dont:

$di->set('myvalidation', function () { 
    require DIR.'/../app/librarys/Myvalidation.php'; 
    return $mycheck; 
}); 

You here only require some file and thats it and return null. Well it should still exists as a service so you are doing something wrong. Show me lines where you defineing those services and getting them and let say + 5 lines above and below.

this is file bootstrap index.php in folder public <?php

use Phalcon\Loader; use Phalcon\Mvc\View; use Phalcon\Mvc\Application; use Phalcon\Di\FactoryDefault; use Phalcon\Mvc\Url as UrlProvider; use Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter;

try {

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

// Create a DI
$di = new FactoryDefault();

 // Setup the database service
$di->set('db', function () {
    return new DbAdapter(array(
        "host"     => "localhost",
        "username" => "root",
        "password" => "",
        "dbname"   => "phalcon_01"
    ));
});

// Setup the view component
$di->set('view', function () {
    $view = new View();
    $view->setViewsDir('../app/views/');
    $view->registerEngines(
        array(
            ".volt" => 'Phalcon\Mvc\View\Engine\Volt'
        )
    );
    return $view;
});

// Setup a base URI so that all generated URIs include the "phalcon_01" folder
$di->set('url', function () {
    $url = new UrlProvider();
    $url->setBaseUri('/phalcon_01/');
    return $url;
});
//injection service
**$di->set('mycheck', function () {
 require __DIR__.'/../app/librarys/Mycheck.php';
 return $mycheck;
});**
//Register route
$di->set(
'router',
    function () {
        require __DIR__.'/../app/config/routes.php';

        return $router;
    }
);
 // Handle the request
$application = new Application($di);

echo $application->handle()->getContent();

} catch (\Exception $e) { echo "Exception: ", $e->getMessage(); } this is file Mycheck.php in forder app/librarys <?php use Phalcon\Validation; use Phalcon\Validation\Validator\Email; use Phalcon\Validation\Validator\PresenceOf; class Mycheck extends Validation {

public function initialize()
{
    $this->add(
        'username',
        new PresenceOf(
            array(
                'message' => 'The user name is required'
            )
        )
    );

    $this->add(
        'email',
        new PresenceOf(
            array(
                'message' => 'The e-mail is required'
            )
        )
    );

    $this->add(
        'email',
        new Email(
            array(
                'message' => 'The e-mail is not valid'
            )
        )
    );
    $this->add(
        'password',
        new Email(
            array(
                'message' => 'The password is required'
            )
        )
    );

}

} $mycheck = new Mycheck(); return $mycheck; this is action in UserController I use service and call mycheck public function authAction(){ if($this->request->isPost()){ $di = new FactoryDefault(); $validation = $di->get("mycheck"); $messages = $validation->validate($_POST); if (count($messages)) { foreach ($messages as $message) { echo $message, '<br>'; } } } $this->view->setRenderLevel(View::LEVEL_ACTION_VIEW); } Please check help me,thank.

Exception: Service 'mycheck' wasn't found in the dependency injection container

edited Mar '16

That need to be in service definition not in required file:

$di->set('mycheck', function () {
 require __DIR__.'/../app/librarys/Mycheck.php';
 $mycheck = new Mycheck(); 
 return $mycheck;
});

Also think about using phalcon loader.

if I define class inside index.php it runs fine. if I use the auto loader it runs fine but I want to use it as $ di-> get ('mycheck') in any controllers as global service and I want to split it up into separate files for easy manager https://docs.phalcon.io/en/latest/reference/di.html#organizing-services-in-files Organizing services in files You can better organize your application by moving the service registration to individual files instead of doing everything in the application’s bootstrap. Example https://stackoverflow.com/questions/24315909/how-to-create-a-new-injectable-service-in-phalcon. I want to move code class JsonService to file JsonService .php in folder app/librarys/JsonService .php and register service for file JsonService.php as $ di-> get ('jsonService') in any controllers as global service. Please help me.

Yes class definition you store in file but Object of this class must be created in service function when you defining service like in code I wrote any in examples.

Please help me example.

edited Mar '16

There is example:

$di->set('mycheck', function () {
 $mycheck = new Mycheck(); 
 return $mycheck;
});
<?php 
use Phalcon\Validation;
use Phalcon\Validation\Validator\Email; 
use Phalcon\Validation\Validator\PresenceOf;

class Mycheck extends Validation {

public function initialize()
{
    $this->add(
        'username',
        new PresenceOf(
            array(
                'message' => 'The user name is required'
            )
        )
    );

    $this->add(
        'email',
        new PresenceOf(
            array(
                'message' => 'The e-mail is required'
            )
        )
    );

    $this->add(
        'email',
        new Email(
            array(
                'message' => 'The e-mail is not valid'
            )
        )
    );
    $this->add(
        'password',
        new Email(
            array(
                'message' => 'The password is required'
            )
        )
    );

}
}

Also use phalcon class loader instead of require in function call:

$loader = new Loader();
$loader->registerDirs(array(
    '../app/controllers/',
    '../app/models/'
));
$loader->registerClasses([
    'Mycheck' => __DIR__.'/../app/librarys/Mycheck.php'
]);
$loader->register();

Example not run and get Error Exception: Service 'myCheck' wasn't found in the dependency injection container

Yes beacause you registered service as mycheck

$di->set('mycheck', function () {
 $mycheck = new Mycheck(); 
 return $mycheck;
});

not myCheck

Make sure they both are the same when you do $di->get and $di->set

Exception: Service 'mycheck' wasn't found in the dependency injection container. It still error

edited Mar '16

Then you are doing something wrong. It works for me.

Put your project to git or something where i can download your whole project cuz you are doing something wrong and i don't know what is this. I give you code, it works for me without any problem.

https://github.com/quannhan1226/phalcon.git Note file index.php in folder/public //injection service $di->set('mycheck', function () { $mycheck = new Mycheck(); return $mycheck; }); Note UserController and authAction Where I use $validation = $di->get("mycheck"); Note file Mycheck.php in folder librarys When I access url: https://localhost/phalcon_01/users/login and I click submit get error..

edited Mar '16

It's commented.... it means this code is not runned in php.

https://php.net/manual/en/language.basic-syntax.comments.php

Learn php first before using any framework

  /*  $di->set('mycheck', function () {
      $mycheck = new Mycheck(); 
      return $mycheck;
    });*/

Also remove $mycheck = new Mycheck(); from index.php under $loader->register();, you dont need it there

thank you.I'm a PHP programmer with 1 year experience. I work with laravel framework and PHP.
I am confused, in fact I'd say. if use clas loader, then not necessary to use $di->set('mycheck', function () { $mycheck = new Mycheck(); return $mycheck; , In Usercontroller only use $mycheck = new Mycheck().if auto load class Mycheck, not $di->get('mycheck'). But I dont want use class loader . I do not want to pre-load multiple files automatically. I only want use lazy load use service when call.

forums support are very enthusiastic, thank

edited Mar '16

It doesn't pre-load your files ! It's building arrays where they are, then that register() method is registering phalcon's autoloader using spl_autoload_register. Then if you access this class somewhere in your code then it's loading this file, not earlier. The same way autoloader works on laravel for example or autoloader from composer. So - phalcon's loader is already using lazy loading. Object of Mycheck is created after $di->get("mycheck") not when you do $di->set("mycheck").

$di->set('mycheck', function () { $mycheck = new Mycheck(); return $mycheck; }

Yes, it's not necessary, but it's better to have registered it as a service instead of using $mycheck = new Mycheck() in every controller when we need it. You have to load it on both cases to be able to use it.

The diffrence in phalcon autloader and example in laravel it's that that laravel is adding automatically all namespaces etc to be used with autoloader. In phalcon you have to select yourself what you want to be autoloaded.

thank you very much. I understand Who are you ? are you use laravel and node Js ?

Im using symfony in one project and phalcon in another.

Bye.thank you very much.



145.0k
Accepted
answer

Well select my answer as solving topic.

Well next time select answer WHICH is solving topic/your problem mostly :P