-1

I envisage developing an API client library which may use many small utility classes. Do I have to have a separate file for each class if using PSR-4? Is my approach sound, and if so how can I achieve it?

Edit in response to answers: I didn't understand the range of autoloading strategies in Composer particularly classmap autoloading and how that can better manage my own codebase.

Useful knowledge from Evert and Jeto.

Sample project layout:

src
  myproject
    client
      apilib.php

apilib.php includes:

class Connection {}
class Statistics {}
class SomeOtherThing {}

Or am I stuck with creating these files?

client/apilib/Connection.php
client/apilib/Statistics.php
client/apilib/SomeOtherThing.php

What namespaces will my classes use?

Dizzley
  • 487
  • 6
  • 16
  • you could plop it all in one file (php or psr autoloading has no limitation on that), its what redbean, adminer etc does, but its don't help you in the long run unless you like scrolling through thousands of lines all day long – Lawrence Cherone Aug 21 '20 at 17:13
  • I find it difficult asking somewhat stupid questions on SO but I'm old enough not to care any more. If it helps me shape my understanding I'm grateful for the answers. I've had trouble aligning my declarations and file organisation with autoloading so that shapes my line of questioning. – Dizzley Aug 21 '20 at 18:01
  • 1
    If you're using composer (which you should), you may use the [`classmap` autoloading](https://getcomposer.org/doc/04-schema.md#classmap) instead, which will scan the files within given directories and load them properly no matter which scheme you decide to follow. Though to be fair using PSR-4 paths/autoloading is probably a better idea as it's become a norm. – Jeto Aug 21 '20 at 18:28

1 Answers1

3

PSR-4 maps classes and namespaces to file and directory paths, but you are not required to follow PSR-4.

Evert
  • 93,428
  • 18
  • 118
  • 189
  • Are you saying that If I am explicit with my namespaces and set the anchor properly e.g MyLib\\\ -> src/ then autoloading should work anyway for me? – Dizzley Aug 21 '20 at 17:50
  • 1
    No, composer has several autoloading strategies. One of them is `psr-4`. You probably want 'classmap' or 'files': https://getcomposer.org/doc/04-schema.md#autoload – Evert Aug 21 '20 at 18:31
  • I realise now how Composer's classmap and files autoloading help me manage my classes.Thanks for clearing up a serious misunderstanding. – Dizzley Aug 22 '20 at 06:13