#what are the cases where i should bind a class in service container

42 messages · Page 1 of 1 (latest)

visual bronze
#

hi i have a class that i have created on a folder that i created named service at the app folder this class is responsible for the uploads of multiple photos to the database this class name is Upload what i want to ask is that there are no need to bind() this to the service container to be able to use it in the controller is that correct?

visual bronze
#

what are the cases where i should bind a class in service container

slow iron
#

@visual bronze You only bind stuff if it needs adding to the service container.

#

If the class can just be instantiated without any dependencies, then Laravel will be able to create it when you type-hint it in your classes.

#

If the class does have dependencies, then you can add a binding that tells Laravel how to create an instance of the class when it’s requested.

visual bronze
#

@slow iron dependencies like parameters that need to be added to the constructor right

slow iron
#

It would be a lot easier if you just showed your code.

visual bronze
#

@slow iron that is the Upload Class

#
<?php

namespace App\Services;

use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Illuminate\Validation\Validator;

class Uploads
{
    protected array|UploadedFile $file;
    protected string $path;
    protected int $size;

    public function __construct(Request $req, string $file = 'files')
    {
        $validator  = $req->validate([
            'files.*' => 'mimes:png|max:2048'
        ]);
        $this->file = $req->file($file);
    }

    public function productsImagesUpload(Product $product,string $storePath): void
    {
        foreach ($this->file as $file){
            $product->pimages()->create([
                'path' => $file->store($storePath,'local'),
                'size' => $file->getSize()
            ]);
        }
    }
}

#

in here it has a Request and a $file Parameter as a string

#

and i didn't create any service provider for that class yes

#

and here is how i used it in my controller

    public function store(Request $request,Uploads $uploads)
    {
        $validated = $request->validate([
            'name' => 'required',
            'description' => 'required',
            'category' => [
                'required',
                Rule::in(['1', '2'])
            ],
            'slug' => 'required',
            'files' => 'required',
/*            'files.*' => 'mimes:png|max:2048'*/
        ]);

        $product = Product::create([
            'name' => $request->get('name'),
            'description' => $request->get('description'),
            'category_id' => $request->get('category'),
            'slug' => $request->get('slug'),
        ]);

        $uploads->productsImagesUpload($product,'Uploads');

        //return view('products.create',['title'=>'Create','message'=>'Products Added']);
    }

slow iron
#

@visual bronze I don’t really see the benefit the class is giving you to be honest. It’s needs instantiating with a Request instance, which only makes it usable in a HTTP context. And all you’re doing is looping over the uploaded files to save them against a product.

visual bronze
#

@slow iron all what i want to do here is just to sperate teh upload fuctionality from the conroller because i want it to lean as mush as i can

slow iron
#

You might be better off extracting the whole of the creating a product to some sort of action class:

class CreateProduct
{
    public function handle(array $data): Product
    {
        $product = Product::create([
            'name' => $data['name'],
            'description' => $data['description'],
            'category_id' => $data['category'],
            'slug' => $data['slug'],
        ]);

        foreach ($data['images'] as $file) {
            $product->pimages()->create([
                'path' => $file->store('uploads', 'local'),
                'size' => $file->size()
            ]);
        }

        return $product;   
    }
}
public function store(StoreProductRequest $request, CreateProduct $creator)
{
    $product = $creator->handle($request->validated());

    // Return response
}
#

You also didn’t really pay attention to me when I said about moving your validation to a form request class, or naming your relation images instead of your weird “pimages” name.

#

You should also probably automatically generate the slug from the name, rather than passing both as request data.

visual bronze
#

yes i know but i ammaking it step by step i take t from down the file uploads to up but i will do itof course

slow iron
#

Considering you were complaining people weren’t replying to your thread, people are definitely going to stop replying to you if you don’t actually act on the advice they give you. People are just going to feel like you’re wasting their time.

visual bronze
#

i am just trying but some times i fail s you know i am still begginner

#

🙂

slow iron
#

So why not stick to what you’ve been told to do, instead of going off on tangents doing something completely different?

#

Why did you try moving uploads to their own class when no one told you to?

visual bronze
#

ok i will do it

slow iron
#

Just a bit strange for someone to tell you to move your validation to a form request, and then go, “OK” and then just go do something completely different (move uploads to a class).

#

Bit of a waste of time me giving you suggestions, you not listening to them and then doing something completely different instead, don’t you think?

visual bronze
#

i agree

slow iron
#

So don’t do it?

visual bronze
#

but i will make the action class know is the action class is deffrent from the request class?

slow iron
#

StoreProductRequest is the form request class. CreateProduct is the action class.

visual bronze
#

ok thank you very much i will do it and send you if i have any problem

visual bronze
#

@slow iron martien you know that i dont mean to waste your time right

visual bronze
#

@slow iron can i separate the upload in a seperate method in the same action class

slow iron
#

Does it make sense to?

#

What are you going to gain?

visual bronze
#

@slow iron hemm i am thinking about it this is one request that are returning a product with all of its stuff so it make scene to make all of the logic in one handle method

visual bronze
visual bronze
# slow iron I dunno. Can you?

here it is the handel method but when i tried to get the file size using
$file->size() i got an execiption
Method Illuminate\Http\UploadedFile::size does not exist.
and here is the code for the handel

    public function handle(array $data): Product
    {
        $product =  Product::create([
            'name' => $data['name'],
            'description' => $data['description'],
            'category_id' => $data['category'],
            'slug' => Str::slug($data['name']),
        ]);

        foreach ($data['files'] as $file) {
            $product->images()->create([
                'path' => $file->store('uploads', 'local'),
                'size' => $file->size()
            ]);
        }

        return $product;
    }