I have a section called as reports and under this there are around 40-50 reports.
For each report i need to define a separate class/controller.
I have created a reports folder under controllers and added a ReportsController class under it. My routes route to this ReportsController's add method and based upon the parameter passed it call's the different report class (like ContainerReportController) add method.
Example code:
controllers/reports/ReportController.php
class ReportController extends BaseController {
public function add($type)
{
$controller = Str::studly($type) . 'Controller';
return $controller::add();
}
}
controllers/reports/ContainerReportController.php
class ContainerController extends BaseController {
public function add()
{
return "Report will be added here and redirected to main page".
}
}
I did it this way because it will not be possible for me to define routes to each of this different types of reports (like ContainerReportController), i defined a single route to the main RportController and from there i call different controllers.
I want to know if i am doing it in right way or if i can have something else which can help me better my code.
FYI - I run composer dump-autoload
after adding each Reports in controller/report directory so that the report class is autoloaded while the application runs.
Please help improve this coding.
Thanks, Nikhil
I think your code is not bad, but here's some improvements:
So you have a route:
Route::get('report/{type}', 'ReportsController@report');
A report controller which will instantiate your report and not use it statically, this is testable:
class ReportsController extends BaseController {
public function report($type)
{
$report = Str::studly($type) . 'Report';
return with(new $report)->add();
}
}
Many report classes extending a BaseReport class.
This is not a controller because controllers should not talk to each other. A controller basically receives a request pass it to a service class or a model, get the procesed data and send it to a view.
class ContainerReport extends BaseReport {
public function add()
{
$this->reportData = "Report will be added here and redirected to main page".
return $this->render();
}
}
And a BaseReport class, which will be extended by all report classes, to do the common things your reports will surely do:
abstract class BaseReport {
protected $reportData;
public function render()
{
return $this->reportData;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.