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

Basic routing doesn't work (404 Not Found)

Hello guys !

Sorry but have very simple problem on my routing, i tried to search on internet/forum but I did not find a solution. I builded my project Phalcon 2days ago with last version of devtool (i followed lastest DOC).

Here a minimal code.

This is my public/index.php :


<?php
use Phalcon\Di\FactoryDefault;

error_reporting(E_ALL);

define('BASE_PATH', dirname(__DIR__));
define('APP_PATH', BASE_PATH . '/app');

try {

    /**
     * The FactoryDefault Dependency Injector automatically registers
     * the services that provide a full stack framework.
     */
    $di = new FactoryDefault();

    /**
     * Handle routes
     */
    include APP_PATH . '/config/router.php';

    /**
     * Read services
     */
    include APP_PATH . '/config/services.php';

    /**
     * Get config service for use in inline setup below
     */
    $config = $di->getConfig();

    /**
     * Include Autoloader
     */
    include APP_PATH . '/config/loader.php';

    /**
     * Handle the request
     */
    $application = new \Phalcon\Mvc\Application($di);

    echo str_replace(["\n","\r","\t"], '', $application->handle()->getContent());

} catch (\Exception $e) {
    echo $e->getMessage() . '<br>';
    echo '<pre>' . $e->getTraceAsString() . '</pre>';
}

This is my app/config/router.php :

<?php

$router = $di->getRouter();

$router->add(
    '/api/currentSong',
    [
        'controller' => 'radio',
        'action'     => 'currentSong',
    ]
);

$router->handle();

This is my app/controllers/RadioController.php :

<?php

class RadioController extends \Phalcon\Mvc\Controller
{
      public function currentSongAction()
      {
          return 'Just a minimal test.';
      }
}

I followed lastest DOC, what is my problem ? :'( thank you in advance for your help.



13.8k
edited Aug '17

How does your app/config/services.php file look like?

Does it have something like this:

/**
 * Loading routes from the routes.php file
 */
$di->set('router', function () {
    return require APP_PATH . '/config/routes.php';
});


2.6k

Nope i have nothing like that ! So i add this news lines :

/**
 * Loading routes from the router.php file
 */
$di->set('router', function () {
    return include APP_PATH . '/config/router.php';
});

But this doesn't work too :'(

For example i have theses lines in service.php

/**
 * Shared configuration service
 */
$di->setShared('config', function () {
    return include APP_PATH . "/config/config.php";
});

(->setShared or just ->set doesn't work for router)



13.8k

Can you try this

Public index

use Phalcon\Di\FactoryDefault;

error_reporting(E_ALL);

define('BASE_PATH', dirname(__DIR__));
define('APP_PATH', BASE_PATH . '/app');

try {

    /**
     * The FactoryDefault Dependency Injector automatically registers
     * the services that provide a full stack framework.
     */
    $di = new FactoryDefault();

    /**
     * Handle routes
     */
    include APP_PATH . '/config/router.php';

    /**
     * Read services
     */
    include APP_PATH . '/config/services.php';

    /**
     * Get config service for use in inline setup below
     */
    $config = $di->getConfig();

    /**
     * Include Autoloader
     */
    include APP_PATH . '/config/loader.php';

    /**
     * Handle the request
     */
    $application = new \Phalcon\Mvc\Application($di);

    echo str_replace(["\n","\r","\t"], '', $application->handle()->getContent());

} catch (\Exception $e) {
    echo $e->getMessage() . '<br>';
    echo '<pre>' . $e->getTraceAsString() . '</pre>';
}

Then in app/config.services.php add

/**
 * The URL component is used to generate all kind of urls in the application
 */
$di->setShared('url', function () {
    $config = $this->getConfig();

    $url = new UrlResolver();
    $url->setBaseUri($config->application->baseUri);

    return $url;
});

/**
 * Loading routes from the routes.php file
 */
$di->set('router', function () {
    return require APP_PATH . '/config/routes.php';
});

Then in app/config/routes.php (bold because I'm using an S on the end)

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

// here your custom routes

return $router;


2.6k

Nop again :(

I added theses lines in services.php :

/**
 * Loading routes from the routes.php file
 */
$di->set('router', function () {
    return require APP_PATH . '/config/routes.php';
});

And create a file app/config/routes.php with theses lines :

<?php 

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

$router->add(
  '/api/currentSong',
  [
    'controller' => 'radio',
    'action'     => 'currentSong',
  ]
);

return $router;

I'm trying to use just the code that DEVTOOL has created (codes in my first post), but it doesn't work, its very strange. Yet it doesn't look complicated.



13.8k

You are right, normally the code generated works out of the box or you'd get an obvious error. How does your app/config/config.php file look like?



2.6k
edited Aug '17

Thanks for your help Videles.

The only thing I did is to replace "// here your custom routes" in app/config/router.php by :

$router->add(
    '/api/currentSong',
    [
        'controller' => 'radio',
        'action'     => 'currentSong',
    ]
);

And create my Controller.

Here my app/config/config.php :

<?php
/*
 * Modified: prepend directory path of current file, because of this file own different ENV under between Apache and command line.
 * NOTE: please remove this comment.
 */
defined('BASE_PATH') || define('BASE_PATH', getenv('BASE_PATH') ?: realpath(dirname(__FILE__) . '/../..'));
defined('APP_PATH') || define('APP_PATH', BASE_PATH . '/app');

return new \Phalcon\Config([
    'database' => [
        'adapter'     => 'Mysql',
        'host'        => 'localhost',
        'username'    => 'root',
        'password'    => '',
        'dbname'      => 'test',
        'charset'     => 'utf8',
    ],
    'application' => [
        'appDir'         => APP_PATH . '/',
        'controllersDir' => APP_PATH . '/controllers/',
        'modelsDir'      => APP_PATH . '/models/',
        'migrationsDir'  => APP_PATH . '/migrations/',
        'viewsDir'       => APP_PATH . '/views/',
        'pluginsDir'     => APP_PATH . '/plugins/',
        'libraryDir'     => APP_PATH . '/library/',
        'cacheDir'       => BASE_PATH . '/cache/',

        // This allows the baseUri to be understand project paths that are not in the root directory
        // of the webpspace.  This will break if the public/index.php entry point is moved or
        // possibly if the web server rewrite rules are changed. This can also be set to a static path.
        'baseUri'        => preg_replace('/public([\/\\\\])index.php$/', '', $_SERVER["PHP_SELF"]),
    ]
]);

PS : My index page work good, just my routing doesn't work.



13.8k

Can you put all the code in a public repo for a moment? I can try to debug it locally then, might be easier



2.6k

Yeap, here a github repo https://github.com/Kakoum/chill-radio.com

Is like my first post here, just with app/config/routes.php in addition (but not use).

Thank you again.



13.8k
Accepted
answer
edited Aug '17

I got it working.

basepath returns a nice layout

/api returns 'test'

/api/currentSong returns 'sugi.wa - urtha1'

/api/currentViewers returns zero

/api/recentSong returns a php error not related to routing

Are you using PHP7 ?

I did a pull request. The changes are in services.php. Also remove routes.php. the default one you use is good



2.6k
edited Aug '17

Oh cool !

Yes i use PHP7 (PHP 7.0.22-0ubuntu0.16.04.1)

On root i have .htrouter.php :

$uri = urldecode(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));

if ($uri !== '/' && file_exists(__DIR__ . '/public' . $uri)) {
    return false;
}

$_GET['_url'] = $_SERVER['REQUEST_URI'];

require_once __DIR__ . '/public/index.php';

and my .htaccess :

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteRule  ^$ public/    [L]
    RewriteRule  (.*) public/$1 [L]
</IfModule>

But well, if you got it working, so my code is ok. Maybe my configuration server (chmod). I would put the subject resolved if i found the solution !

Edit : I didn't see your last sentence, ok I will see that !



2.6k
edited Aug '17

Its works !! After you saying my code is ok, i checked my config server and yes was Apache2 conf who ignored htaccess of Phalcon directory root ! (and pointed to /public and not root). Phalcon was working from the beginning ! :o

Thank to you Videles !



13.8k

Ah good that it works, Nice interface for the landing page btw! The .htrouter file is -don't hang me on it- for if you want to use the build in webserver, which you can start up via command line, you could remove it. The routes.php file you added is not being used, your first file was ok so you can remove that aswell. The stuff i added in the service file you could still use. It's probably more convenient during development.

Good luck man!



2.6k

Ok for all and thank ! :)

good continuation !