Předaná metoda končí chybovou hláškou: Call to a member function on null
- egin_28
- Člen | 10
Zdravím,
něco mi patrně uniká při použití DI. Můj cíl je mít v HomepagePresenteru render metodu, která se z mého modelu „DatabaseRecords“ připojí a vypíše všechny řádky v DB.
HomepagePresenter
<?php
namespace App\Presenters;
use Nette
use App\Model\DatabaseRecords;
class HomepagePresenter extends BasePresenter
{
/**@var DatabaseRecords @inject */
public $databaseRecords;
public function renderDefault()
{
$this->template->records = $this->databaseRecords->findDatabaseRecords();
}
}
?>
A DatabaseRecords
<?php
namespace App\Model;
use Nette;
class DatabaseRecords
{
use Nette\SmartObject;
/** @var Nette\Database\Context */
private $database;
public function __construct(Nette\Database\Context $database)
{
$this->database = $database;
}
public function findDatabaseRecords()
{
$this->database->query('SELECT * FROM radius_records;');
}
}
?>
Servisu mám registrovanou v configu:
- services
- App\Model\UserManager
- App\Forms\FormFactory
- App\Forms\SignInFormFactory
- App\Forms\SignUpFormFactory
- App\Model\DatabaseRecords
router: App\RouterFactory::createRouter
A celý toto snažení končí v laděncě: Call to a member function findDatabaseRecords() on null
IDE mi ale v HomepagePresenteru metody z DatabaseRecords našeptává, čili tam jí mam přidanou. Proč tedy metodu „findDatabaseRecords“ hodnotí jako prázdnou?
Děkuji za rady
Editoval egin_28 (1. 5. 2018 18:14)
- kiCkZ
- Člen | 153
Musíš totiž ten dotaz vrátit pomocí return:
public function findDatabaseRecords()
{
return $this->database->query('SELECT * FROM radius_records');
}
V případe inject musíš uvést celou cestu viz ukázka a také odstraň z use toto App\Model\DatabaseRecords.
/** @var \App\Model\DatabaseRecords @inject */
public $databaseRecords;
Editoval kiCkZ (1. 5. 2018 18:26)
- Ondřej Kubíček
- Člen | 494
@egin_28 jen ještě opravím, že v tom docbloku to můžeš mít
zapsané tak jak jsi měl, a s pomocí use, nemusí tam být celý namespace
´
cc @kiCkZ