V
V
vrazbros2021-06-23 15:25:00
PHP
vrazbros, 2021-06-23 15:25:00

An example of a strategy pattern in PHP?

Hello

I'm understanding the strategy pattern and basically I stumble upon an example like this in which we do something like this:
1 Create a class object that is responsible for some algorithm
2 Create a class object where the algorithm is used, pass the dependency through the constructor and then use it through the class property.

can someone give a real example in php? what if the algorithm depends on the data in the request? in the controller add a bunch of if with the help of which the algorithm will be selected?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Daria Motorina, 2021-06-23
@vrazbros

doctrine cookbook: strategy introduction
Zend Hydrator Monolog
- Handling strategy in Fingers Crossed handler

D
Denis, 2021-06-23
@sidni

Well, if, in a simple way, the whole idea is this (too lazy to write code)
1) You create a bunch of class objects where the request processing algorithm will be
1.1) you implement the do ($ request) method in each of this object - the request processing itself
1.2) you implement the can method in each of these objects ($request) - not the entire request is possible, but some flag, this method will return true if this object is suitable for processing this request
2) Create an object of the strategy processing class
, then the can method can be made static)
2.3) you implement the do($request) method where you loop through each strategy by calling the can method and for the one that returned true you call do($request)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question