1

Now I have this:

abstract class PermissionModelAbstract implements PermissionModelInterface
{
    public function setDataValidator(string $action, string $method, DataPermissionValidatorInterface $validator = null)
    {
        if (is_null($validator)) {
            $validator = new DefaultDataValidator();
        }
        $this->model[$action . '/' . $method]['validator'] = $validator;
    }
}

I want to have something like:

abstract class PermissionModelAbstract implements PermissionModelInterface
{
    public function setDataValidator(string $action, string $method, DataPermissionValidatorInterface $validator = new DefaultDataValidator())
    {
        $this->model[$action . '/' . $method]['validator'] = $validator;
    }
}

Is there exists some way to do it?

6
  • 2
    That's the proper way to do it. What's wrong with it? Commented Dec 27, 2013 at 19:40
  • 1
    @onetrickpony , no, it isn't. You cannot construct new instances as default parameters. Try learning PHP. tnxbye Commented Dec 27, 2013 at 19:46
  • I was referring to the first code snippet. And I'm curious why OP is seeking a different way Commented Dec 27, 2013 at 19:49
  • 1
    He want to use a factory/builder, but is yet unaware of it. Commented Dec 27, 2013 at 19:50
  • string $action, do you have string class? Commented Dec 27, 2013 at 19:57

2 Answers 2

1

I'd get rid of calling new inside the method altogether. It introduces tight coupling plus the expectation that a setFoo() setter would be called without the actual foo is bizarre.

Keep the type check in the signature:

public function setDataValidator(string $action, string $method, DataPermissionValidatorInterface $validator);

Then simply provide the dependency "manually" when calling the method:

myPermissionModel->setDataValidator('foo', 'bar', new DataPermissonValidator());

Sign up to request clarification or add additional context in comments.

Comments

0

No other way of doing it, AFAIK.

If you have many dependencies to the point it gets cumbersome to maintain, consider using a Dependency Injection Container.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.