docs icon indicating copy to clipboard operation
docs copied to clipboard

Create abstract class for services in docs

Open inzanty opened this issue 3 years ago • 3 comments

https://doc.nette.org/en/quickstart/home-page

On my opinion, it's could be more better to use abstract class for database than creating in each class property $database and set it in __construct();

namespace App\Presenters;

use Nette;
use Nette\Application\UI\Form;

final class HomepagePresenter extends Nette\Application\UI\Presenter
{
	private Nette\Database\Explorer $database;

	public function __construct(Nette\Database\Explorer $database)
	{
		$this->database = $database;
	}

	// ...
}

Can be changed for:

<?php

declare(strict_types=1);

namespace App\Presenters;

use Nette;

final class HomepagePresenter extends AbstractPresenter
{
	// ...
}

AbstractPresenter.php:

<?php

declare(strict_types=1);

namespace App\Presenters;

use Nette;

abstract class AbstractPresenter extends Nette\Application\UI\Presenter
{
	protected Nette\Database\Explorer $database;

	/**
	 * @param Nette\Database\Explorer $database
	 */
	public function __construct(Nette\Database\Explorer $database)
	{
		parent::__construct();
		$this->database = $database;
	}
}

After that it can be simple called like:

$this->database

inzanty avatar Jan 25 '22 15:01 inzanty

Of course, you're free to do that. Please use the forum for discussion https://forum.nette.org.

dg avatar Jan 25 '22 15:01 dg

It's just suggestion for newbies. I thought it could be useful in docs.

inzanty avatar Jan 25 '22 15:01 inzanty

This is more of a general PHP thing and not specifically related to the framework. However, there is something about it in the documentation: https://doc.nette.org/cs/dependency-injection/passing-dependencies

dg avatar Jan 25 '22 15:01 dg