Answer the question
In order to leave comments, you need to log in
How to call a class through a router?
Here I have a class for loading and resizing images. Yes, the bike is still the same, but I'm just learning.
class Picture
{
protected $img;
private $type = array('image/jpeg','image/png');
public $size = 300000;
public function __construct($img)
{
$this -> img = $img;
$this -> checked($img);
$this -> getSize($img);
$this -> rename($img);
}
protected function checked($img){
if(in_array($img['type'],$this->type)){
return $this;
} else {
exit('Что это? '. $this->img['type']);
}
}
private function getSize($img)
{
if($img['size'] < $this -> size){
return $this;
} else {
exit("Максимальный размер файла:".$this->size);
}
}
private function rename()
{
$name = md5(uniqid($this->img['name']));
$extension = pathinfo($this -> img['name'],PATHINFO_EXTENSION);
$this-> img['name'] = $name.'.'. $extension;
return $this;
}
public function save()
{
move_uploaded_file($this->img['tmp_name'],$_SERVER['DOCUMENT_ROOT']."/image/".$this->img['name']);
return $this;
}
public function resize($new_width)
{
list($width, $height) = getimagesize($_SERVER['DOCUMENT_ROOT'].'/image/'.$this -> img['name']);
$d = $height/$width;
$new_height = $new_width*$d;
$base = imagecreatetruecolor($new_width,$new_height);
if($this->img['type']==='image/jpeg')
{
$source = imagecreatefromjpeg($_SERVER['DOCUMENT_ROOT'].'/image/'.$this -> img['name']);
}
else
{
$source = imagecreatefrompng($_SERVER['DOCUMENT_ROOT'].'/image/'.$this -> img['name']);
}
imagecopyresampled($base,$source,0,0,0,0,$new_width,$new_height,$width,$height);
imagejpeg($base, 'image/small-'.$this->img['name']);
return $this;
}
}
$img = new Picture($_FILES['images']);
$img-> save()
-> resize(600);
Route::get('user/profile', [
'as' => 'profile', 'uses' => '[email protected]'
]);
Answer the question
In order to leave comments, you need to log in
I will duplicate what should be called by the controller in the router.
And also I will add from myself:
Laravel has a class for working with files, look at the documentation
laravel.su/docs/5.4/filesystem
And also ONE of the ways to use your class:
1. You must use the namespace App namespace, since Classes are loaded via autoloader.php - composer
2. Create a library folder, in the /app directory, it should look like this: /app/library and fill in the php file with your class
3. For your class, use the namespace App\Library
4. In the controller that handles the route, include your class:
use App\Library\Picture
5. Refer to your class as Picture::staticMethod() or new Picture;
I think you'll figure it out
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question