I am currently working with a PHP program who uses class inheritance to customize one method. This leads to a code duplication, as the new method is exactly the same and the only change in the new class is the location of one object being imported. Here it is a simplification of the files:
Base class:
namespace Syncs\Common;
use Syncs\Common\Order;
class OrderSync
{
public function processData($data, &$results){
$order = new Order($data);
// Logic to fill results array
}
//Other functions
}
Extending class:
namespace Syncs\Custom;
use Syncs\Custom\Order; // Custom instead of Common
class OrderSync extends \Syncs\Common\OrderSync
{
public function processData($data, &$results){
$order = new Order($data);
// Logic to fill results array (exact same code as parent function)
}
}
As you can see, the only difference is the object Order being created from different source.
There are more classes extending from the base OrderSync and all of them are duplicating the code inside function processData(). There is some way how to avoid this?
CodePudding user response:
You just have to rethink how you initiate the variable $order
. You could create a method createOrder
in the parent class which returns a Syncs\Common\Order
instance and override this in the child class to return a Syncs\Custom\Order
use Syncs\Common\Order;
class OrderSync
{
public function processData($data, &$results){
$order = $this->createOrder($data);
// Logic to fill results array
}
protected function createOrder($order) {
return new Order($data);
}
//Other functions
}
use Syncs\Custom\Order;
class OrderSync extends \Syncs\Common\OrderSync {
protected function createOrder($order) {
return new Order($data);
}
}
CodePudding user response:
You could also move the logic to a trait, for example:
<?php
trait OrderTrait {
public function processOrder($data, &$results)
{
$order = new Order($data);
// logic
return $order;
}
}
class OrderSync
{
use OrderTrait;
public function processData($data, &$results)
{
$order = $this->processOrder($data, &$results);
}
}
CodePudding user response:
use Final
keyword to avoid override method , for example
class Foo
{
final function bar(){
}
}
class X extends Foo
{
public function bar(); //this line will throw error,you cant override this method
}