RomkaLTU
RomkaLTU

Reputation: 4129

Phalcon php namespaces cant use

So I have Users model namespaced:

namespace App\Models;

use Phalcon\Mvc\Model;

class Users extends Model
{

And Controller:

use \Phalcon\Mvc\Controller;
use \App\Models\Users;

class LoginController extends Controller
{
  ...
  public function postLoginAction() {
    $user = Users::findFirst([ ...
  }
  ...

Always getting error Fatal error: Uncaught Error: Class 'App\Models\Users' not found in no matter what, tried every variation no idea what's wrong with it. even my IDEA resolving this class correctly.

Everything is working if I remove my namespacing.

UPDATE:

So if you generated project with phalcon dev tools and then started generate other things (model, controllers) you will need to provide namespace for model and it will not work, you will also need to update app/config/loader.php like this:

<?php

$loader = new \Phalcon\Loader();

/**
 * We're a registering a set of directories taken from the configuration file
 */
$loader->registerDirs(
    [
        $config->application->controllersDir,
        $config->application->modelsDir
    ]
)->register();

$loader->registerNamespaces(
    [
        'App\Controller' => $config->application->controllersDir,
        'App\Model' => $config->application->modelsDir,
    ]
)->register();

In other words register namespace, I don't know why this not clearly stated in documentation but it seams this framework have many such "black holes" or I don't understand this framework fundamentals (came from codeigniter and Laravel background).

Upvotes: 1

Views: 1027

Answers (1)

YOMorales
YOMorales

Reputation: 1966

Try this in your bootstrap file:

// registers namespaces
$loader = new Loader();
$loader->registerNamespaces([
    'App\Controllers' => APP_PATH . '/controllers/',
    'App\Models' => APP_PATH . '/models/'
]);
$loader->register();

Btw, APP_PATH could be a constant to your app's directory, or whatever you want/need.

Upvotes: 1

Related Questions