I have made an API and a trait with a function to handle responses.
namespace AppTraits;
use AppModelsUser;
use AppModelsDiseases;
use AppModelsExaminations;
use AppModelsRec_Doc;
use AppHttpResourcesfailter;
trait ApiTraits
{
public function apiGet($id = null, $table)
{
if ($table::find($id)) {
$status = '200';
$message = 'ok';
$data = new failter($table::find($id));
} elseif ($id === null) {
$data = failter::collection($table::get());
$status = '303';
$message = 'getting all data';
} else {
$data = null;
$status = '404';
$message = 'not found';
}
$array = [
'data' => $data,
'status' => $status,
'message' => $message
];
return $array;
}
}
After that, in the controller, I use this function:
public function users()
{
return $this->apiGet('','User');
}
The expected scenario is getting =>
$data = failter::collection($table::get());
$status = '303';
$message = 'getting all data';
Getting error =>
Class "User" not found
But I already added a User model.
3
Answers
The class isn’t called
User
it’s actually calledAppModelsUser
. When you putuse AppModelsUser
at the top of your file, it installs a shorthand for that file where every time you refer to the barewordUser
what you actually mean isAppModelsUser
. Strings (e.g.$cls='Foo';new $cls;
) do not get the same treatment.Try using the
::class
notation in the controller:::class
makes the bareword into a string with the fully qualified class name.Using
::class
instead of the stringified class name is a good habit to get into because it makes refactoring easier, and the code is easier to read too, sinceUser::class
is clear that it’s a class name, whereas'User'
(string) could be anything.you must use the full path to the class
AppModelsUser
Instead of just defining the model name (User), you can try defining it with full namespaces;
AppModelsUser
orUser::class
.