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

ModeL::findFirst should return instance of extending class

Hey there,

I'm wondering why findFirst method returns a instance of Phalcon\Mvc\Model instead of the extending class. At least this is what the API doc tells me so IntelliJ 2018.1 with the Phalcon Plugin complains about this

function getUser(int $id): User {
    return User::findFirst(3); // Expected return type User but got Phalcon\Mvc\Model
}

$user = getUser(3);

Whats the proper way to do this here? Better pass the model as param to the constructor like new User(User::findFirst(3)) or use db adapter directly?

Thanks in advance

Hi Tomás Phalcon does this automatically. You probably have a small error in your definitions. Check this

// User model definition
class User extends \Phalcon\Mvc\Model {}

// where is defined
use \yourNameSpace\User;

function getUser(int $id): User {
    return User::findFirst(3); // Expected return type User but got Phalcon\Mvc\Model
}

// concider this to avoid problems with return type
// php <= 7.0
function getUser(int $id): User {
    $user = User::findFirst(3); 

    if (!$user instanceof User) {
        throw new \Exception('User not found');
    }

    return $user;
}

// php >= 7.1
function getUser(int $id): ?User {
    return User::findFirst(3) ?: null;
}

Good luck