In the past, I've always opted to write scripts for my sites (such as things that did DB modifications, pre-load data, etc) via sequential code, meaning something like
$mysql = new PDO();
$data = $mysql->query();
$updatedData = doSomething($data);
$mysql->query(... $updatedData ...);
At most, I'll include a file at the top that sets up stuff like my DB, includes helper functions, etc. However, I've been noticing a lot scripts get written as a single class containing a main method (often exec
or something similar), which is called once.
The only advantage I can see to this is the ability to extend off a base class which sets up variables. Is there some big advantage to single-class scripts that I'm missing? Or is this the natural progression for OOP languages? Mind you, when I'm writing more complex code, I always opt for classes, but for whatever reason, seems strange for scripts...
-
2I would say that not everything should be expressed as an object. If the logic just needs a sequential list of software component actions then that would seem to be the most appropriate expression.Richard Chambers– Richard Chambers2017年12月26日 14:42:23 +00:00Commented Dec 26, 2017 at 14:42
1 Answer 1
There isn’t any benefit to be had in refactoring your program into a single class. When using OOP, you will have the most benefit in refactoring to many smaller classes which each have a single responsibility, and work together to accomplish the task at hand. The idea of a class is to encapsulate state and expose behaviors (methods) that act upon that state. For instance, you could have a class that encapsulates the database connection information, and exposes methods for accessing and mutating data within the database. Often, that type of abstraction works well in tandem with domain driven design. For a set of good OOP guidelines to follow, look into the SOLID programming practices.