0

It's quite random to me if I need to have a use statement to access a class. In the following code, which runs without issues, the Faker library doesn't need use Faker or something like that, yet the Seeder does need an use.

I assume Faker is accessed using the Composer autoloader, yet in composer.json I don't see the vendor directory being used for either the psr-4 autoload or the classmap autoload, so how it finds this is beyond me.

<?php

use Illuminate\Database\Seeder;


class MoreProductsSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        for ($i = 0; $i<1000; $i++)
        {
            $faker = Faker\Factory::create();
            \App\Product::create([
                'name' => $faker->name,
                'photo' => 'https://picsum.photos/200/300',
                'price' => rand(1,20000),
                'category_id' => rand(1,3)
            ]);
        }
      
    }
}
Nico Haase
  • 11,420
  • 35
  • 43
  • 69
Plumpie
  • 426
  • 1
  • 6
  • 22
  • Does this answer your question? [How and where should I use the keyword "use" in php](https://stackoverflow.com/questions/43136277/how-and-where-should-i-use-the-keyword-use-in-php) – Nico Haase Jul 23 '20 at 11:32
  • Not really, I know the concept behind `use` but don't understand how exactly that plays out in my specific example. – Plumpie Jul 23 '20 at 15:33
  • Some classes are available as aliases of loaded service providers. Some of examples are `DB`, `Log` etc. You can find full list in `config/app.php` file. – Tpojka Jul 24 '20 at 05:52

1 Answers1

0

If you are using a class multiple times, for e.g
Faker\Factory::create(...)
.
.
.
then, in the same file you use
Faker\Factory::create(...) again.

Here you are repeating the full path Faker\Factory, rather you should just use Faker\Factory as Faker; before the class and then simply use the Faker::create(...) as many time you want without repeating the full path.

You can even do class MoreProductsSeeder extends Illuminate\Database\Seeder this instead if you prefer it.

Digvijay
  • 7,836
  • 3
  • 32
  • 53
  • You're right that my code could be optimized, but your answer isn't really an answer to my question – Plumpie Jul 23 '20 at 15:30