If you’re writing a class that relies on something outside if PHP, how do you manage that? What I mean is, I can use dependency injection to show one class depends on another. What if my class requires a certain version of JQuery, for example? Do you just put that in the comments at the top?
Secondly, if you’re writing a class that queries a database and you think it might get used in another project, do you bother to add the database structure to the comments? Or do you right the class so all database tables and column names are customisable? I can’t help thinking the latter is good in an ideal world but perhaps overkill for most projects.
I know there is no right or wrong answer here but would be interested all the same. I don’t know but for me, I always like to make code as reusable as possible—especially if I’m writing classes.
I’m currently writing a package that generates, validates and processed a form. The validation is done with JQuery (if JavaScript is enabled). Mostly you can keep things like that separate but some classes (though a small minority) will inevitably output front-end code dynamically that relies on a client-side library.
So, the class doesn’t rely on JQuery as such, rather the site should include the appropriate version of JQuery in the head. Does that makes sense?
With the database table point, (very) simply put an example would be:
class Foo1 {
function __construct($foo) {
$query = "SELECT * FROM `table` WHERE `column` = '{$foo}'";
}
}
Versus:
class Foo2 {
function __construct($foo, $table, $column) {
$query = "SELECT * FROM `{$table}` WHERE `{$column}` = '{$foo}'";
}
}
Do you consider it bad practice to do it the Foo1 way? That is, the class it dependent on a particular database table names/columns. There’s less to pass to Foo1 but Foo2 is easier to use in other projects.
I’d just list jQuery as a requirement in your package’s documentation.
In the case of your class that deals with the DB, if the DB structure changes then the class would have to change, but if as you’ve isolated the dependency on the table structure to that one class then the rest of your app should continue to work as before.