1

Well, i keep hearing that you better not get use of static methods in php, i can understand that to some extent, But there are some confusions for me, what i want to know is :

Let's say i'm writing an application, i define hundreds of classes ( Or use a framework which already contains hundreds of different classes ), i don't know if i should create a class for each small task, so lets say i create a class for handling all CRUD tasks for a particular item ( for example blog posts ), and this class handles viewing, saving, editing and etc, in such case, if i instantiate the class each time, it will create an object containing mostly methods that we don't need in that request, so... I guess what i'm trying to ask is:

Is it wise to do something like that? Create classes containing methods a lot of them we don't use in each request, and define them as non-static, so each time we'd have to instantiate the whole object?

Like Laravel does for it's controllers, we define all non-static methods to handle all tasks related to a certain route group, and instantiate the whole controller each time we want to access one or two of those methods.

Thanks in advance for your time and patience. I appreciate it.

Arsi
  • 191
  • 1
  • 1
  • 10
  • 1
    In general you implement a class for every "thing" you design, not for "actions". The instantiation of an object in deed is costly, but that does not depend much on the number or size of the methods implemented in the class. As often the advantage of readability and reusability of the code is _far_ more important. – arkascha Jun 22 '16 at 12:49

1 Answers1

1

What you see in most of the frameworks is that a CRUD is written in a Controller. This is the way it is supposed to be.

One controller has multiple actions (create, read, update and delete). The thing is that these methods aren't all called and executed. If you want to read your blog posts, the only thing that will be executed is the read action.

You could compare it with driving cars. You can store multiple 'cars' in one 'garage' but you can only drive one at a time.

To add some more information. When you create an instance of a class:

$class = new myClass();

The only thing that will be called (if present) is the constructor.

public function __construct()
{
    // Instantiation logic here
}

By creating an instance of this class you don't actually execute all the methods. You will just make them available to use. (Like opening the garage door and handing you the car keys :D )

Peter
  • 8,776
  • 6
  • 62
  • 95