Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Possibility to "merge" properties in user land #553

Open
nikophil opened this issue Feb 2, 2024 · 1 comment
Open

Possibility to "merge" properties in user land #553

nikophil opened this issue Feb 2, 2024 · 1 comment

Comments

@nikophil
Copy link
Member

nikophil commented Feb 2, 2024

From time to time there is the need to "merge" properties.

Given the following code:

// BlogPostFactory

public function defaults(): array
{
    return [
        'tags' => []
    ];
}

public function taggedWithPhp(): static 
{
    return $this->withAttributes(['tags' => ['php']]);
}

public function taggedWithSymfony(): static 
{
    return $this->withAttributes(['tags' => ['symfony']]);
}

It is not possible have a nice fluent api to have both tags php and symfony. I could do something like BlogPostFactory::createOne(['tags' => ['php', 'symfony']]), but real world examples are much less naive :)

Another example would be with a bitmask:

$filePermissionsFactory->withRead()->withWrite()->withExecute();

I think there could be several solutions to mitigate this problem:

  • make Factory::$attributeSet protected, and let the user deal with it "at his own risk"
  • create a new method Factory::mergeAttributes(array), but this may come at the cost of some complexity (should we "deeply" merge array, objects, factories, etc... ?
  • create a new method Factory::resolveAttribute(string) which could be used in some cases to access the state of a given attribute.

not sure what would be the best solution 🤔

@kbond
Copy link
Member

kbond commented Feb 2, 2024

Does this work?

// BlogPostFactory

public function defaults(): array
{
    return [
        'tags' => []
    ];
}

public function taggedWithPhp(): static 
{
    return $this->beforeInstantiate(function(array $attributes) {
        $attribtues['tags'][] = 'php';

        return $attributes;
    });
}

public function taggedWithSymfony(): static 
{
    return $this->beforeInstantiate(function(array $attributes) {
        $attribtues['tags'][] = 'symfony';

        return $attributes;
    });
}

If so, this feels like the best method to give complete control. We could make a helper but, like you say, do we deep merge?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants