First contact with the PHP abstract factory pattern of Elgg

  • 2020-03-31 20:28:22
  • OfStack

I want to achieve such a function: launch a website invitation activity, then the participant (owner) will promote the website address link to friends, friends click the link after the successful registration in the website, the number of owner's invitation log record increased by 1.
Action classes Activity
 
class Activity extends ElggEntity { 
private $strategy; //To save the policy instance
public function __construction($guid) { 
... 
$this->load($guid); //Load the entity
} 
public function addLog($data) { 
$this->strategy->addLog($data); //Is actually DEFAULTActivityStrategy: : addLog ($data)
} 
public function load ($guid) { 
if (parent::load($guid)) { //This process assigns all the properties of this instance from the database, so $this-> The value of strategyName has been assigned.
if ($this->strategyName != '') { 
$this->strategy = AbstractActivityStrategy::getInstance($this->strategyName); //Load policy class
} 
return true; 
} 
return false; 
} 
} 

The log class ActivityLog
 
class ActivityLog extends ElggEntity { 
$private countValue; //Number of invitation records
... 
} 

Strategy class
ElggEntity: all entity base classes. AbstractActivityStrategy: active abstract class
) first create an activity:
 
$activity = new Activity(); 
$activity->name = 'KKND'; //The name of the event
$activity->strategyName = 'DEFAULT'; //Name of strategy
$activity->save(); //The active class is saved to the database, as are the newly added attributes, such as strategyName

) when someone receives an invitation, click the link and the owner's invitation record entry +1
Such as inviting the url is http://www.xinwusi.com/KKND/1234
Where /KKND/ is the name of the activity and 1234 is the guid of the owner. Suppose the guid of the activity is 8888, then
$activity = new activity (8888); // gets the active entity
$activity - > AddLog ($data); // add the invitation record. $data includes the guid of the owner, the guid of the activity, the name of the activity, and so on.
The last two lines of code read the policy name of the active entity, generate a policy entity based on that policy name, store it in its own $stragety property, and call the addLog method to increase the logging.
Later, when there is a new activity, directly change the policy name of the activity instance property, you can call the method in the corresponding new policy.
 
class DEFAULTActivityStrategy extends AbstractActivityStrategy { 
... 
public function addLog($data) { 
$activityLog = new ActivityLog(); 
... 
$activityLog->save(); 
$activityLogAmount = new ActivityLogAmount(); //Counting class
... 
$activityLogAmount->countValue += 1; 
$activityLogAmount->save(); 
} 
} 

Related articles: