0

When using composer PSR autoloading, imagine having a PHP file with 5.000 (yes, i know this might be bad practice) lines. This file contains 1 class & make use of many different models or libraries within. Is it then better for performance to put a 'use' statement for each class that i reference or is it better to put a 'use' statement for each namespace that i reference? I'm thinking of the later. Just because i sort of expect that composer autoload when the class is referenced. So when referencing the namespace rather than the actual class initially it will first autoload the class when it's called from within the file.

Example showcasing use of class reference in 'use' statements:

<?php
use Framework\Models\User;
use Framework\Models\Pages;
use Framework\Models\Security;
use Framework\Models\Books;

class Example {
  public function userExample() { return User::example(); }
  public function pagesExample() { return Pages::example(); }
  public function securityExample() { return Security::example(); }
  public function booksExample() { return Books::example(); }
}

Example showcasing use of namespace reference in 'use' statements:

<?php
use Framework\Models;

class Example {
  public function userExample() { return Models\User::example(); }
  public function pagesExample() { return Models\Pages::example(); }
  public function securityExample() { return Models\Security::example(); }
  public function booksExample() { return Models\Books::example(); }
}

Can anyone clarify how composer actually autoload? Will it in example #1 require the class immediately or will it stil wait for the class to have something invoked?

danniehansenweb
  • 465
  • 4
  • 14
  • Premature optimization alert… `Can anyone clarify how composer actually autoload` it doesn't autoload, PHP autoloads classes, Composer only tells it where the files are located – Mike Doe Oct 04 '19 at 06:58
  • It doesnt matter both ways hit the autoloader with the same value – Lawrence Cherone Oct 04 '19 at 07:37
  • There is a significant difference between the 2 approach if you throw in a ridiculous amount of subclass and use statement. Please see the [benchmark here](https://github.com/yookoala/benchmark-php-use). But I'm sure the difference is insignificant in real life. – Koala Yeung Oct 04 '19 at 08:34
  • I used a custom written autoloader instead of composer's autoloader. But I don't think it matters at all. – Koala Yeung Oct 04 '19 at 08:45

0 Answers0