In my class, we made a simple application using MVC with the observer pattern in Java and it works. The view cannot call any methods from the model that are not included in the (Observable) interface and vice versa.
I am quite a fan of PHP and decided to make the same (simplified) example in PHP. I noticed that even though I am using an interface and passing the reference of the model as an interface, the view can still call every method inside the model, rendering the entire pattern useless.
Is there something I overlooked or is this not possible in PHP?
The PHP code (every reference, method, etc is the exact same as in the Java application) :
class App
{
public function __construct()
{
$model = new Model();
$controller = new Controller($model);
}
}
class Model implements Observable
{
private $view;
private $count = 1;
public function __construct()
{
echo 'Model created. <br>';
}
public function registrate(Observer $view)
{
$this->view = $view;
echo 'Model: view is registered. <br>';
}
public function addOne()
{
$this->count += 1;
$this->view->modelChanged($this);
}
public function getCounter()
{
return $this->count;
}
public function getMessage()
{
return 'The view should not be able to call this method.';
}
}
class Controller
{
private $view;
private $model;
public function __construct(Model $model)
{
echo 'Controller created. <br>';
$this->model = $model;
$this->view = new View($this->model);
$this->model->addOne();
}
}
class View implements Observer
{
public function __construct(Observable $model)
{
echo 'View created. <br>';
$model->registrate($this);
}
public function modelChanged(Observable $model)
{
// Should only be able to call method "getCounter()"
echo $model->getMessage();
}
}
interface Observable
{
public function registrate(Observer $view);
public function getCounter();
}
interface Observer
{
public function modelChanged(Observable $model);
}
The output, if you run this is:
Model created.
Controller created.
View created.
Model: view is registered.
The view should not be able to call this method. As you can see, the view can call a method of the model that is not declared inside the Observable interface.
How is this possible and why does this not work in PHP like it does in Java?
Well of course the view can call every method you've defined on the model: All the methods are public, which means they're callable from anywhere. Just define them as protected or private instead...
Of course, that'd limit the ways in which you can use the model in other components (such as the controller). To get around that problem, a simple fix would be to create a wrapper, which you can wrap around the model when you pass it to the view:
class View implements Observable
{
public function __construct(ViewObservable $model)
{
//do stuff here
}
}
//Wrapper:
class ViewObservable
{
/**
* #var Model
*/
protected $payload = null;
public class __construct(Observable $model)
{
$this->payload = $model;
}
public function getCounter()
{
return $this->payload->getCounter();
}
}
But really, you might want to rethink a thing or 2. It's good to use interfaces, but it doesn't make a lot of sense (to me at least) to have all components in an MVC architecture implement the same interface. All components have different jobs to perform, and therefore should have different interface requirements.
Related
I have a following structure to use Open Close Principle
class Payment{
//this is not a model class
// according to OC principle this class should not focus on the implementation
private $paymentInterface;
public function __construct(PaymentInterface $paymentInterface)
{
$this->paymentInterface = $paymentInterface;
}
//so store method does not know which implementation it will get
public function store($request,$id)
{
return $this->paymentInterface->store($request,$id);
}
}
Interface
interface PaymentInterface{
public function store($request,$id = null);
}
Payment Service Class containing implementation
class PaymentService implements PaymentInterface{
public function store($request,$id = null){
//payment store logic is here
}
}
Controller
class PaymentsController extends Controller{
protected $payment;
public function __construct()
{
$this->payment = new Payment(new PaymentService);
}
public function storePayment(PaymentRequest $request, $id)
{
try {
$response = $this->payment->store($request,$id);
return redirect()->route($this->route.'.index')->with($response['status'],$response['message']);
} catch (\Exception $e) {
return $this->vendorDashboard($e);
}
}
}
My question is:
Is it correct approach to use Open-Close-Principle ?
Using above code I can tell controller that I can use PaymentService class for the implementation.
$payment = new Payment(new PaymentService);
return $payment->store($request,$id);
If later I want to make a payment in different way e.g. make a payment through invoice then I can create new controller, write new implementation in new class e.g. InvoicePaymentService and tell Payment class to use InvoicePaymentService as implementation
$payment = new Payment(new InvoicePaymentService);
return $payment->store($request,$id);
OR
$payment = new Payment(new PayPalPaymentService);
return $payment->store($request,$id);
OR
$payment = new Payment(new AliPayPaymentService);
return $payment->store($request,$id);
I know I can bind Interface with a class through a service provider but if I want to implement a different payment implementation then I will not be able to change the class, right ?
If I am doing it in wrong way please let me know.
This is what service container stands for. You should use contextual binding
Assuming you have an interface: FooInterface
And you have two concrete implementations: GoodFoo and BadFoo
In order to inject different implementations to controllers (or other classes) you must tell it to laravel.
$this->app->when(GoodController::class)
->needs(FooInterface::class)
->give(function () {
return new GoodFoo();
});
$this->app->when(BadController::class)
->needs(FooInterface::class)
->give(function () {
return new BadFoo();
});
And controllers should be:
class GoodController extends Controller
{
protected $foo;
public function __construct(FooInterface $foo)
{
$this->foo = $foo;
}
}
class BadController extends Controller
{
protected $foo;
public function __construct(FooInterface $foo)
{
$this->foo = $foo;
}
}
Please note that most of the time laravel promotes bad software design principles and it rather hard to practise SOLID principles in laravel.
Unfortunately I'm stuck here.
Consider the following rudimentary examples:
interface ChargeInterface
{
public function charge($amount);
}
class BraintreeCharge implements ChargeInterface
{
public function charge($amount)
{
// braintree logic here
}
}
class StripeCharge implements ChargeInterface
{
public function charge($amount)
{
// stripe logic here
}
}
So there's an interface for charging a payment method, and there are, in this example, two concrete classes which implement the interface.
I'd like to be able to decide on runtime which implementation should be used. So I thought I'd achieve this with custom factory classes:
class PaymentFactory
{
public static $implementation;
public static function charge()
{
return $implementation::charge();
}
}
class StripeFactory
{
public static function charge()
{
return new StripeCharge();
}
}
class BraintreeFactory
{
public static function charge()
{
return new BraintreeCharge();
}
}
Than I could just use the factories:
PaymentFactory::$implemention = StripeFactory::class;
$payments = PaymentFactory::charge();
$payments->charge(100);
Another idea was to use a singleton based logic:
class PaymentFactory extends Singleton
{
protected $implementation;
// Singleton logic missing in this example
public function useImplementation($class)
{
$this->implementation = $class;
}
public function getImplementation()
{
return $this->implementation;
}
public static function charge()
{
$instance = self::getInstance();
return new $instance->getImplementation();
}
}
Later ...
PaymentFactory::getInstance()->useImplementation(StripeCharge::class);
$payments = PaymentFactory::charge();
$payments->charge(100);
Do you've any suggestions regarding best practices here?
I think I'd favour the first one, since the real implementation consists of more than just one class per package, as outlined in the example.
Also it seems to me, this would be the more cleaner way.
I am using CodeIgniter and have extended CI_Model. so all my models now extend MY_Model.
This works fine.
Issue is that all my models have a secondary associated object. basically a class that gets passed data from the model (usually from the database) and represents that row in the database.
so something like
class Product_Model extends MY_Model{
public function get($id){
//....
return new Product($query->row());
}
}
class Product{
public function __construct(stdClass $data){
//....
self::$ci =& get_instance();
self::$model = self::$ci->products;
}
}
Now I load the Product_Model with an alias $this->load->model('product_model', 'products');
Hence having self::$model = self::$ci->products;
But now I want to have a basic class that all the classes like Product will extend.
I want this to contain the logic to update self::$model.
But I need to know the models alias.
Something like
self::$model = self::$ci->{instantiator_variable_name($this)} which would be self::$model = self::$ci->products
Now obviously that function does not exist but it shows what I want to do.
I know I could for everywhere that I create the Product or similar have
$row = $query->row();
$row->model = $this->ci->products;
return new Product($row);
But I would rather automate it if I could.
It might help if you clarify the situation a bit. Post a bit more of your code please?
For example, Modals (in CodeIgniter) are generally used as singleton classes which (almost) explains using 'self::" but it looks like you want Product to be an Object. So why does that use
self::$model
instead of
$this->model
The fact that you're aliasing the products model makes me think you might be doing this on purpose (which is why I'm confused, why would you do this?). I think you should review the difference between "self::", "static::", and "$this->". Take a look at http://php.net/manual/en/language.oop5.late-static-bindings.php
rockstarz is correct, you need to use the Factory Pattern. Consider something like this:
class ItemFactory {
private $model;
public function __construct($model) {
$this->model = $model;
}
function create_product(stdClass $data) {
$product = new Product($data);
$product->set_model($this->model);
return $product
}
}
abstract class Item {
protected $model;
protected $ci = & get_instance();
public function __construct(stdClass $data) {
// whatever
}
public function set_model($model) {
$this->$model = $model;
}
public function get_model() {
return $this->model;
}
}
class Product extends Item {
// whatever
}
Then your model can just use it like
class Product_Model extends MY_Model {
private $item_factory;
public function __construct() {
$this->item_factory = new ItemFactory($this);
}
public function get($id){
return $this->item_factory->create_product($row);
}
}
Relevant reading materials:
http://en.wikipedia.org/wiki/Inversion_of_control#Implementation_techniques
http://en.wikipedia.org/wiki/Factory_method_pattern
http://en.wikipedia.org/wiki/Dependency_injection
Is it ok to put factory() method to the factoried object's class?
class User {
public static function factory($id) {
return new User($id);
}
private function __construct($id) {
}
}
And when consider placing factory() method into separated class?
class User {
public function __construct($id) {
}
}
class UserFactory {
public static function factory($id) {
return new User($id)
}
}
I can't see any benefits of using additional class for factory, but I consider that there are some benefits I don't know about. :)
When to put factory() method into factoried object and when put factory() method to separated class?
The advantage with putting the factory method inside the class itself is protecting the class from being instantiated without using the factory method:
class User {
public static function factory($id) {
return new User($id);
}
private function __construct($id) {
// Now, only the factory method within this class can call this method.
// (Additionally, this method was static, which it shouldn't.)
}
}
I let other add to this with advantages of the opposite solution.
If you have a static creator method there is not much use in putting in into a factory.
It's only really useful to put factory method in it's own class if it isn't static and you want to inject it somewhere.
class User {
public static function __construct($id) {
}
}
class UserFactory {
public function factory($id) {
return new User($id)
}
}
class SomethingUserReleated {
public function __construct(UserFactory $factory) {
$this->userFactory = $factory;
}
public function iNeedToCreateAnUserForSomething() {
$userOne = $this->userFactory->factory(1233);
$userTwo = $this->userFactory->factory(123533);
}
}
Since you can't to the above with static methods.
Moving the factory methods into separate class allows you to separate object-methods and factory-specific methods (that are only needed while creating a new object).
class User {
public static function __construct($id, $name){
// call this directly or via Factory
}
}
class UserFactory {
private static function randomName(){
// return some random name
}
public static function factory($id){
return new User($id, UserFactory::randomName());
}
}
Given a Controller class and a View class, is it better for the controller to directly assign values to view properties or, is it better to assign values to properties in the controller and then copy those properties to the view when ready to display it?
Example Model Class
class Model
{
public $propertyA;
public $propertyB;
}
Example Controller class:
class Controller
{
protected $view;
protected $model;
public function __construct()
{
$this->model = new Model();
$this->view = new View();
$this->prepareData();
$this->initView();
}
protected function prepareData()
{
$this->model->propertyA = 'This is property A.';
$this->model->propertyB = 'This is property B.';
}
protected function initView()
{
$this->view->model = $this->model;
$this->view->display();
}
}
Example View class:
class View
{
public $model;
public function display()
{
echo "propertyA = $this->model->propertyA";
echo "propertyB = $this->model->propertyB";
}
}
Sorry, I was tired. I do use a model, so please reconsider your answers with this in mind.
The data should only be in one place. If not when things get complicated it is hard to sync the different places you have the data. In MVC you have a model and that is where the data should be. Pass the Model into the View and have the view display that.
Here is a simple explanation: http://en.wikipedia.org/wiki/Model%E2%80%93View%E2%80%93Controller or here for those that do not like Wikipedia: http://ootips.org/mvc-pattern.html
The model can be as simple as a class with the properties in it.
The view shouldn't be setting up variables unless they are related to the presentation. It's best to put static variables in a config file anyway.
copy those properties to the view
Rather than setting variables in the view why don't you just construct the view with a reference to the controller. That should save you from writing a lot of boiler plate code.
Class Controller() {
$this->something = 'abc';
function __construct() {
$this->display();
}
function display() {
$this->view = new View($this);
}
}
Class View() {
function View(&$controller) {
$this->controller = $controller;
print $this->controller->something;
}
}
Edit: I like Romain Hippeau's answer a lot more than my own. You should pass the model into the view.