I have something like a shop. It is limited to a checkout page, which will send an email. Nothing big, but a nice thing to learn more OOP.
Almost every time I develop new classes I am wondering how to organize the flow of depending methods. Here is an example, a first draft of what I have:
<?php
// Outside the class:
if (!empty($cms->request->post('add_to_cart'))) {
$cart->addStrt();
}
OPTION A
// OPTION A: Build a "method chain" and move from one to the other, to the next …
Class Cart extends Shop {
// This is the entry point and starts the "add process"
public function addStart() {
$this->checkQuantity(); // if qty is between min/max
return false;
}
// Step 2
public function checkQuantity() {
if ($quantity < $max && $quantity > $min) {
$this->checkInStock(); // move on to the next step
}
return false;
}
// Step 3
public function checkInStock() {
if ($availabe >= $qty_in_basket) {
$this->addToCart(); // move on to the final step
}
return false;
}
// Step 4
public function addToCart() {
// Final step, all requirements ok
$product_id = $this->request->post->product_id;
$cart = $this->getCart();
$product = $shop->getProduct($product_id);
$cart->items->add($product);
$added = $cart->save();
return $added;
}
}
OPTION B
// OPTION B: Have a single "add" method and check all requirements, sanitize, etc from a single method
Class Cart extends Shop {
public function add() {
$continue = $this->checkQuantity(); // if qty is between min/max
if ($continue == false) return false;
$continue = $this->checkInStock(); // if product still available
if ($continue == false) return false;
// Perhaps more checks, sanitize, etc.
// Everythiing mus be ok, put item into cart
$product_id = $this->request->post->product_id;
$cart = $this->getCart();
$product = $shop->getProduct($product_id);
$cart->items->add($product);
$added = $cart->save();
return $added;
}
}
I have read tutorials on some OOP patterns but can't seem to find which fits to my question. While Option B seems to be cleaner (to understand/extend) one thing I always read is never put multiple tasks into one method. Every method should only handle one specific task. But how/where do I control the flow?
Is this "Encapsulation" or "Decorator pattern" or "Dependency Injection"? I have no idea what I should google.
false
? \$\endgroup\$$continue = $this->checkInStock(); if ($continue == false) return false;
to justif (!$this->checkInStock()) return false;
by the way. \$\endgroup\$checkInStock()
to return a boolean which tells you if it's in stock or not. The methods in option A all returningfalse
makes no sense though. \$\endgroup\$