Lets say I intiialize a class, but I have conditionals in my script which may mean that the class methods never actually get used.
Example:
$rr = new RecipientRepo($db);
if ($_GET['action'] == 'test1') {
$rr->showForm1();
}
else if ($_GET['action'] == 'test2') {
$rr->showForm2();
}
If that conditional isn't met then the methods of the class would never be called.
Is this poor practice? I'd prefer this over initializing the class within every single condition.
Any answers would be appreciated.
Initialize the class only if the key is set in $_GET. You can do this -
if (!empty($_GET['action'])) {
$rr = new RecipientRepo($db);
if ($_GET['action'] == 'test1') {
$rr->showForm1();
}
else if ($_GET['action'] == 'test2') {
$rr->showForm2();
}
}
If you want to make it more specific then -
if (!empty($_GET['action']) && in_array($_GET['action'], array('test1', 'test2'))) {
If initializing the class is resource-intensive, you can initialize it depending on if you need it. If the RecipientRepo object is closely tied to form submissions, you could even add a static method in the object to determine if you need to create it:
public static function formPosted() {
return (
isset($_GET['action']) &&
in_array($_GET['action'], array(
'test1',
'test2'
))
);
}
Then, in your main form, you could call it to determine if you need to instantiate an object:
if (RecipientRepo::formPosted()) {
$rr = new RecipientRepo($db);
if ($_GET['action'] == 'test1') {
$rr->showForm1();
}
else if ($_GET['action'] == 'test2') {
$rr->showForm2();
}
}
Wrapping this logic in a method ensures that you only instantiate your object when the proper conditions are correct. It also encapsulates the logic for determining when to do this in an easy-to-read structure.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With