0

In PHP, you can have a collection as an array as a class property. This collection can have a function add that takes multiple (type-hinted) parameters, as such: add( Markup $markup, Style $style = Null), the keyword here is Null, the system tells you that "hey, you don't have to add this, but you can do it, but it has to be of type Style)" and adds a package to that internal array:

public function add( $name, Markup $markup, Style $style = Null )
{
    $this->packages[$name]['markup'] = $markup;

    if( $style ) {
        $this->packages[$name]['style'] = $style;
    }
}

Which means that 100% a package has a markup object, but it can have a style as well.

Thing is - watch what happens when, by good intentions, I just wanna have things separated such that my interfaces aren't cluttered:

public function add( $name, Markup $markup, Style $style = Null, Categorized $categories, .. )
{
    $this->packages[$name]['markup'] = $markup;

    if( $style ) {
        $this->packages[$name]['style] = $style;
    }

    if( $categories ) {
        $this->packages[$name]['categories'] = $categories;
    }

    //.. and so on, gets cluttered.
}

This ramps up to be Satan-level hectic to maintain.

What is a solution to this?

8
  • doesnt this overwrite the contents of packages[$name]?
    – Ewan
    Commented Jan 14, 2020 at 9:40
  • Fixed. Adds to the package.
    – Daniel M
    Commented Jan 14, 2020 at 12:05
  • surely you should add a null style if not supplied in order to maintain the overall class
    – Ewan
    Commented Jan 14, 2020 at 12:51
  • @Ewan Right, but the question is how do I do this at scale? I'll end up with a lot of parameters and a lot of checks.
    – Daniel M
    Commented Jan 14, 2020 at 13:39
  • why check at all, just add null
    – Ewan
    Commented Jan 14, 2020 at 13:46

1 Answer 1

1

Its unclear to me exactly what you are trying to do. I would have this:

public function add(Package $p)
{
    $this->packages[$p.name] = $p;
}

class Package
{
    public $Name
    public $Style 
    public $Categorized  
}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.