How to get dependencies in model?
- TonnyVlcek
- Member | 31
Hey,
At first I apologies for that elementary question, but, unfortunately, I haven't been able to find a way how to make this work, even though I tried a good bit of variants.
I need to call some method form different model class inside another model class:
<?php
class AaRepository extends BaseRepository
{
public function getFromAa(){}
}
...
class BbRepository extends BaseRepository
{
public function createSomething(){
if([here I would like to call method getFromAa()]){}
}
}
?>
Is there a way how to “inject” AaRepository into BbRepository so I can use Aa's methods? (both of those services are registered in config.neon services)
Basically I have to do exactly the same think like in presenters:
<?php
/** @var \Namespace\Class @inject */
public myRepository;
?>
or somehow get the service directly from DI container.
Thank you very much for your answers :)
Last edited by TonnyVlcek (2015-01-03 19:20)
- newPOPE
- Member | 648
Hi,
“somehow get the service directly from DI container.” is not a good access.
And if you need AARepository
in BBRepository
just
write a dependency in constructor and DI container build the service
for you.
Example:
class BBRepository extends BaseRepository {
public function __construct (AARepository $aaRepository) {
// now you have AARepository here...
}
}
- TonnyVlcek
- Member | 31
Ok, thank you, now I know where was the mistake.
I red that I should use constructor injection in model classes, but it always
gave me a fatal error which was caused by my implementation.
Because of I'm extending from BaseRepository with its __construct method:
<?php
class BaseRepository extends Nette\Object
{
function __construct($table, Context $context)
{
$this->context = $context;
$this->table = $table;
}
}
?>
I have to use this syntax inside of other model classes:
<?php
public function __construct($table, Nette\Database\Context $context, TeamsRepository $teamsRepository)
{
parent::__construct($table, $context);
$this->teamsRepository = $teamsRepository;
}
?>
Now it works how it is supposed to :)
I'm posting this for someone who maybe came across the same problem. Please, in case that this is not correct or best practice, let me know what I can do differently, thanks :)