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

Multimodule app probelm with loading BaseController

In a single app solution this controller code works:

BaseController.php: ```php <?php

class BaseController extends \Phalcon\Mvc\Controller {

// code

}


IndexController.php:
```php <?php 

class IndexController extends BaseController 
{

// code

}

however in multimodule app I am getting this error:

Fatal error: Class 'Multiple\Apps\Frontend\Controllers\BaseController' not found

Why is that? What am I doing wrong? In single app it worked ;(

my app structure is exactly like here:

https://docs.phalcon.io/en/latest/reference/applications.html#multi-module



8.1k

You can use the namespace to get around this obstacle.



13.6k

@Oleg could you be more specific? I don't know how to do that.



13.6k

how canI do that? There is nothing on controllers for multimodule apps in the documentation ;(



13.6k

This is my BaseController (located inside apps/frontend/controllers):

```php <?php

class BaseController extends \Phalcon\Mvc\Controller {

public function initialize() 
{
    // CSS
    $this->assets
        ->collection('style')
        ->addCss('third-party/css/bootstrap/bootstrap.min.css', false, false)
        ->addCss('css/style.css')
        ->setTargetPath('css/production.css')
        ->setTargetUri('css/production.css')
        ->join(true)
        ->addFilter(new \Phalcon\Assets\Filters\Cssmin());

    // JS
    $this->assets
        ->collection('js')
        ->addJs('third-party/js/jquery/jquery.min.js', false, false)
        ->addJs('third-party/js/bootstrap/bootstrap.min.js', false, false)
        ->setTargetPath('js/production.js')
        ->setTargetUri('js/production.js')
        ->join(true)
        ->addFilter(new \Phalcon\Assets\Filters\Jsmin());
}

}

and this is my IndexController (the same location as BaseController):

```php <?php 

class IndexController extends BaseController 
{

    public function indexAction() 
    {
        echo __FUNCTION__;
    }

}

But it's not loaded. I am getting this error:

Fatal error: Class 'BaseController' not found in C:\wamp\www\2014\facebookclone\apps\frontend\controllers\IndexController.php on line 4


13.6k

Please, help me if you know the answer. Thanks you.



13.6k

I tried this:

class IndexController extends Multiple\Frontend\Module

because I am using this in my index.php in the public folder:

<?php

error_reporting(E_ALL);

class Application extends \Phalcon\Mvc\Application
{

        /**
         * Register the services here to make them general or register in the ModuleDefinition to make them module-specific
         */
        protected function _registerServices()
        {

                $di = new \Phalcon\DI\FactoryDefault();

                $loader = new \Phalcon\Loader();

                /**
                 * We're a registering a set of directories taken from the configuration file
                 */
                $loader->registerDirs(
                        array(
                                __DIR__ . '/../apps/library/'
                        )
                )->register();

                //Registering a router
                $di->set('router', function(){

                        $router = new \Phalcon\Mvc\Router();

                        $router->setDefaultModule("frontend");

                        $router->add('/:controller/:action', array(
                                'module' => 'frontend',
                                'controller' => 1,
                                'action' => 2,
                        ));

                        $router->add("/login", array(
                                'module' => 'backend',
                                'controller' => 'login',
                                'action' => 'index',
                        ));

                        $router->add("/admin/products/:action", array(
                                'module' => 'backend',
                                'controller' => 'products',
                                'action' => 1,
                        ));

                        $router->add("/products/:action", array(
                                'module' => 'frontend',
                                'controller' => 'products',
                                'action' => 1,
                        ));

                        return $router;

                });

                $this->setDI($di);
        }

        public function main()
        {

                $this->_registerServices();

                //Register the installed modules
                $this->registerModules(array(
                        'frontend' => array(
                                'className' => 'Multiple\Frontend\Module',
                                'path' => '../apps/frontend/Module.php'
                        ),
                        'backend' => array(
                                'className' => 'Multiple\Backend\Module',
                                'path' => '../apps/backend/Module.php'
                        )
                ));

                echo $this->handle()->getContent();
        }

}

$application = new Application();
$application->main();

But then I am getting this error: txt Fatal error: Uncaught exception 'Phalcon\Mvc\Dispatcher\Exception' with message 'Multiple\Frontend\Controllers\IndexController handler class cannot be loaded' in C:\wamp\www\2014\facebookclone\public\index.php on line 82



8.1k

See, please https://github.com/oleg578/Phalconskeletonmulti There you will find the answer. You can regisry namespaces of controllers, and you can set namespace of controllers before. There is repository with tracking, debugiing and work code.



13.6k

@Oleg I have told you that I don't know what namespace should I use. Please, provide the example . Thank yo in advance.



13.6k

@Oleg And If you are creating an example, please, if it's called "MULTI" provide at least the second module/app e.g. "backend". Otherwise it's "SINGLE". Sorry, but the Phalcon examples and documentation are so inconsistent and sometimes so damn brief, that it drives me crazy.



13.6k

I tried from your example:


<?php

namespace Multiple\Apps\Frontend\Controllers; 
class IndexController extends \Phalcon\Mvc\Controller 
{

    public function indexAction() 
    {
        echo __FUNCTION__;
    }

}

And I am still getting: txt Fatal error: Uncaught exception 'Phalcon\Mvc\Dispatcher\Exception' with message 'Multiple\Frontend\Controllers\IndexController handler class cannot be loaded'



13.6k

Btw. your .htaccess is missing inthe sceletonformultiapps. Please, update it so other people who are less experienced don't have problems. Or at least mention it in your readme that some files are missing.



13.6k

Your code in App.php:

```php <?php

namespace Multiple\Apps;

class App extends \Phalcon\Mvc\Application {

use \Services;

public function main() {

    $this->_registerServices();

    $this->registerModules( array(
        'frontend' => array(
            'className' => 'Multiple\Apps\Frontend\FrontendModule',
            'path'      => dirname(__DIR__) . '/apps/frontend/FrontendModule.php'
        ),
    ));
    echo $this->handle()->getContent();

}

}```

is giving me this error:

txt Parse error: syntax error, unexpected T_USE, expecting T_FUNCTION in C:\wamp\www\2014\facebookclone\apps\App.php on line 10

Please, explain what is the problem in your code and how can I solve it. My php version is 5.3.13 . PLease, what is wrong with "use", how can I change it to work with my version of php?



8.1k

Unfortunately, I do not use Apache in their practice. I only use Nginx and Lighttpd. And I don't use Windows at all. In any case, you can use htaccess from documentation. Аll requests are redirected to public directory, no features. Or you can use built-in PHP-server, start it in public directory like

php -S localhost:8000 -t /your_project_directory/public/
PHP 5.5.8 (cli) (built: Jan 10 2014 15:34:09) 
Copyright (c) 1997-2013 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2013 Zend Technologies
    with Xdebug v2.2.3, Copyright (c) 2002-2013, by Derick Rethans
Linux  3.12.7-1-ARCH #1 SMP PREEMPT Fri Jan 10 08:50:35 CET 2014 x86_64 GNU/Linux
curl https://localhost:8000
<!DOCTYPE html>
<html>
    <head>
        <title>Multi</title>
    </head>
    <body>
        <section>
    </section>
<h3>Index action</h3>
<hr>
<p>
    Multiple\Apps\Frontend\Controllers\IndexController</p>
<hr>
<p>
    indexAction</p>    </body>
</html>


13.6k

@Oleg Could you help with the "use" problem (unexpected T_USE), please? Thank you.



8.1k

<?php
namespace Multiple\Apps;

class App extends \Phalcon\Mvc\Application {

   /**
    * use trait from config/Services.php
    */
    use \Services;

    public function main() {

        $this->_registerServices();
        /**
         * register module Frontend
         */
        $this->registerModules( array(
            'frontend' => array(
                'className' => 'Multiple\Apps\Frontend\FrontendModule',  // register namespace
                'path'      => dirname(__DIR__) . '/apps/frontend/FrontendModule.php'  // registaer module Frontend
            ),
        ));
        echo $this->handle()->getContent();

    }

}


13.6k

@Oleg What did you change? To me it seems the same.



8.1k

You use old version of PHP, may be. You can use require_once instead trait. Or install latest PHP from https://www.php.net



8.1k

You can use require_once instead trait. Or just copypast this function from Services.php



13.6k

@Oleg require_once is not working when I try this:

<?php

trait Services {

    protected function _registerServices() {

        $di = new \Phalcon\DI\FactoryDefault();

...

changing to this:

```php<?php

require_once Services {

protected function _registerServices() {

    $di = new \Phalcon\DI\FactoryDefault();

...



8.1k

Just delete lines on start

trait Services {

and on the end

}

And copypast this function to class App after :)

<?php

namespace Multiple\Apps;

/**
 * Description of App
 *
 * @author Oleh Nahornyi
 *
 */
class App extends \Phalcon\Mvc\Application {

   // use \Services;
    protected function _registerServices() {

        $di = new \Phalcon\DI\FactoryDefault();

        /**
         * Register config
         */
        $di->set('config', function() {
            $config = new \Phalcon\Config\Adapter\Ini(
                    dirname(__DIR__) . '/config/config.ini');
            return $config;
        });
        /**
         * Register annotations
         */
        $di->set('annotations', function() {
            return new \Phalcon\Annotations\Adapter\Memory();
        });
        /**
         * Register routes
         */
        $di->set('router', function () {
            $router = new \Phalcon\Mvc\Router\Annotations(\FALSE);
            $router->removeExtraSlashes(\TRUE);
            $router->setUriSource(
                    \Phalcon\Mvc\Router\Annotations::URI_SOURCE_SERVER_REQUEST_URI);
            $router->addModuleResource(
                    'frontend', 'Multiple\Apps\Frontend\Controllers\Index', '/');
            $router->setDefaultModule('frontend');
            $router->notFound([
                "controller" => "index",
                "action"     => "page404"
            ]);
            return $router;
        });

        /**
         * set URL
         */
        $di->set('url', function() {
            $url = new \Phalcon\Mvc\Url();
            $url->setBaseUri('/');
            return $url;
        });

        /**
         * flash service
         */
        $di->set('flash', function() {
            return new \Phalcon\Flash\Direct([
                'error'   => 'alert alert-error',
                'success' => 'alert alert-success',
                'notice'  => 'alert alert-notice',
                'warning' => 'alert alert-warning',
            ]);
        });

        /**
         * Register Coockie Service
         */
        $di->set('cookies', function() {
            $cookies = new \Phalcon\Http\Response\Cookies();
            $cookies->useEncryption(TRUE);
            return $cookies;
        });
        /**
         * Register session
         */
        $di->setShared('session', function() {
            $session = new \Phalcon\Session\Adapter\Files();
            $session->setoptions([
                'uniqueId' => 'privatRsc',
            ]);
            $session->start();
            return $session;
        });
        /**
         * Crypt Service
         */
        $di->set('crypt', function() use($di) {
            $crypt = new \Phalcon\Crypt();
            $crypt->setKey($di->getConfig()->phalcon->secretkey);
            return $crypt;
        });

        /**
         * Form manager
         */
        $di->set('forms', function() {
            $forms = new \Phalcon\Forms\Manager();
            /**
             * set form example
             */
            // $forms->set('userform', new ActorForm());
            return $forms;
        });
        $this->setDI($di);
    }

    public function main() {

        $this->_registerServices();

        $this->registerModules([
            'frontend' => [
                'className' =>
                'Multiple\Apps\Frontend\FrontendModule',
                'path'      =>
                dirname(__DIR__) . '/apps/frontend/FrontendModule.php'
            ],
        ]);
        print $this->handle()->getContent();
    }

}


13.6k

Thanks, I am finally getting 404 page so, it's probably working. Now I need to set the routes.

Btw. why I am getting 404 page for indexAction?


class IndexController extends \Phalcon\Mvc\Controller {

    /**
     * @Get("/")
     */
    public function indexAction() {
        $this->view->setVars( array(
            'class'  => __CLASS__,
            'action' => __FUNCTION__,
        ));
        echo "This is index";
    }```


13.6k

IN your routes settings you have this:

         /**
         * Register routes
         */
        $di->set('router', function () {
            $router = new \Phalcon\Mvc\Router\Annotations(\FALSE);
            $router->removeExtraSlashes(\TRUE);
            $router->setUriSource(
                    \Phalcon\Mvc\Router\Annotations::URI_SOURCE_SERVER_REQUEST_URI);
            $router->addModuleResource('frontend', 'Multiple\Apps\Frontend\Controllers\Index', '/');
            $router->setDefaultModule('frontend');
            $router->notFound( array(
                "controller" => "index",
                "action"     => "page404"
            ));
            return $router;
        });

and I would like to set the default homepage to indexAcion in IndexController.php like:

        /**
         * Register routes
         */
        $di->set('router', function () {
            $router = new \Phalcon\Mvc\Router\Annotations(\FALSE);
            $router->removeExtraSlashes(\TRUE);
            $router->setUriSource(
                    \Phalcon\Mvc\Router\Annotations::URI_SOURCE_SERVER_REQUEST_URI);
            $router->addModuleResource('frontend', 'Multiple\Apps\Frontend\Controllers\Index', '/');
            $router->setDefaultModule('frontend');

            // here I tried to set the home route
            $router->add('/', array(
                'controller' => 'index',
                'action'     => 'index',
            ));

            $router->notFound( array(
                "controller" => "index",
                "action"     => "page404"
            ));
            return $router;
        });

But it's not working how to do that in your code?



8.1k
$router->notFound([
                "controller" => "index",
                "action"     => "page404"
            ]);

to

$router->notFound([
                "controller" => "index",
                "action"     => "index"
            ]);

may be. But, there is the bad practice...



8.1k

There is Annotations using in this skeleton. And

$router->add('/', array(...

could not be working. You can reset the router without Annotation. See documentation about.



13.6k

Where can I find your documentation about routes?



13.6k

@oleg578 I don't understand. Could you proide some code for e.g. testAction?

In normal Phalcon website it would work automatically, but in your code I am getting error Page not found 404.

Could you provide some example code for some Action of your choice from teh INdexController.php?



13.6k

Or could somebody else help? If I didn't solve this problem I would need to find some other code. The problem is that there is no admin and frontend tutorial on the internet so far. Only some bootstrap single app unfinished tutorials. And this framework is out more a year. It's a shame that there is no admin frontend tutorial.



8.1k

I know and use only Linux, and I don't know Windows. And I create aplications on php5.5 now. On older version of php you can use compatible consruction, such as replace consruction [] to array() etc.



13.6k

The operationg system or PHP version is not a problem right now. The main problem with your code is that it is without documentation and what is more problematic (at least for somebody wh is not a phalcon professional), that it doesn't have any 2nd module, just one called frontend, but if you call it "multi" (that means more than 1) you shall provide at least something like "backend" or "admin"etc. together with your current module "frontend". Of course, it's just my opinion, but think about that if possible ;).



8.1k

This entire skeleton is made on the basis of documentation of Phalcon. Code is easy. And therefore does not require comments I added a backend module for clarity. It is very easy to do, you can now see.



13.6k

Thanks a lot, I will try your reworked skeleton. But remember, what is easy for you could be hard for somebody else, at least from the beginning ;). I am pretty sure that playing a violin is hard for you, but not so much for me, benn practicing violin for more than a decade. Therefore projecting your own values and experience is not always the best approach when considering difficulty of something.



8.1k

I meant that the code Phalcon uses simple lexical class names. And the code is easy to read thanks to the developers Phalcon. According to established practice, this code is not accepted to comment. Sufficient knowledge of the language PHP and OOP medium for understanding. I advise you to carefully examine the documentation of the Dependensy Injection of Phalcon. Then you will have fewer questions. I wish you success in your projects.



13.6k

@Oleg I have tried your skeleton app on a Linux machine (Ubuntu php 5.4.16) and it's not working either. I am affraid that your code has many bugs. Please, make a notice in your repository, that your code needs more work to be complete and without bugs. It's not fair to other people offering something that is not working without telling them that it's not wokring.

I am getting this for all actions even the homepage:

txt Multiple 404 - route not found

Maybe this link could help you with polishing your code https://github.com/dphn/SkeletonApplication



8.1k

Now I do :

git clone [email protected]:oleg578/Phalconskeletonmulti.git

then

php -S localhost:9000 -t /home/test/Phalconskeletonmulti/Multiple/public/

and

curl https://localhost:9000/admin/show

and have the result

[Mon Jan 13 16:57:44 2014] ::1:42648 [200]: /admin/show
<!DOCTYPE html>
<html>
    <head>
        <title>Multiple</title>
    </head>
    <body>
        <h1>Multiple</h1>
        <section>
    </section>
<h1>Backend</h1>
<h3>Show action</h3>
<hr>
<p>
    Multiple\Apps\Backend\Controllers\IndexController</p>
<hr>
<p>
    showAction</p>    </body>
</html>

My system: Archlinux kernel 3.12.7 PHP 5.5.8

Your UBUNTU ok, are you sure? Such a configuration works well for Debian 7 and on realy server in WEB...



8.1k

And by the way, what you suggested h...s://github.com/dphn/S....., created with many violations PSR.



13.6k

@Oleg you are using highly customized system without bacwards compatibility. Please, note these facts in your git repo. Otherwise you are misleading users of other platforms. Thanks.



8.1k

In contrast, my system, including production servers, constructed entirely in accordance with the standards of Linux and web-servers. I'm just guessing that you are missing some knowledge, such as PHP and servers. I have any projects basic Phalcon in production, and I can't agree with you. Those operations are elementary. They require minimal knowledge. Very sorry that you are having difficulties.



13.6k

For God's sake, it's not Linux but GNU/Linux, so no, you are not using "standard" practices. Please, be a little more down-to-earth. Thank you.