I know this has been covered in pieces before, but I am struggling with how to apply it to my code.
I am developing a PHP application in Laravel but want to make my code more modular and testable, which means pulling my logic away from my heavyset controllers and separating them out into separate files and calling them from within the controller.
In one such controller (ImageController
), I am calling upon the logic in ImageRepository.php
and it looks like this:
<?php
namespace App\Http\Controllers;
use App\Logic\Image\ImageRepository;
use Illuminate\Support\Facades\Input;
class ImageController extends Controller
{
protected $image;
public function __construct(ImageRepository $imageRepository)
{
$this->image = $imageRepository;
}
public function getUpload()
{
return view('pages.upload');
}
public function postUpload()
{
$photo = Input::all();
$response = $this->image->upload($photo);
return $response;
}
/*public function deleteUpload()
{
$filename = Input::get('id');
if(!$filename)
{
return 0;
}
$response = $this->image->delete( $filename );
return $response;
}
*/
}
My problem is I don't understand how this code works, as I got it from another source and want to understand it so I can replicate this architecture elsewhere in my code.
My route when uploading an image is this:
Route::post('upload_image', ['as' => 'upload-post', 'uses' =>'ImageController@postUpload']);
So my first question is, I never call the construct function in my route. It goes right to postUpload()
. Does this mean it has no purpose? Also why does the construct function not have a comma between ImageRepository
and $imageRepository
... from my understanding of the docs you only do that if one of them is a boolean?
Also why does $response = $this->image->upload($photo);
mean anything in postUpload()
? That function upload()
comes from the Repository, is use
enough so that it knows what to do? Why does $this->image
mean anything, what does the $this
refer to? The ImageController
class? Is the image
in $this->image
derived from protected $image
?
I guess I should have stuck with regular PHP before moving to the Laravel framework because while I can navigate through Laravel easily enough to make a working application, it seems to be hindering my ability to follow best practices / architecture. AFAIK a controller is mainly something to manipulate data and send it to the view or the database, I don't understand perhaps why it is a class?
Sorry for the multiple questions I am just very confused. I taught myself php on codeacademy but their class declarations and object instances are very easy to follow, this is not. If someone could explain the code to me that would be very helpful.
Thank you!