thephpleague / factory-muffin

Enables the rapid creation of objects for testing
https://factory-muffin.thephpleague.com/
MIT License
532 stars 72 forks source link

What is `$fm` in the factory definitions? #449

Closed flyingL123 closed 6 years ago

flyingL123 commented 6 years ago

I have read the v3 documentation 100 times and looked through the tests. I still can not understand how to properly use the $fm variable when defining factories.

I see that in the tests themselves we set static::$fm to be equal to an instance of \League\FactoryMuffin\FactoryMuffin. That I understand.

But in the factory definitions, for example in app/test/factories/all.php, there are methods being called on a $fm variable before it is actually defined anywhere. For example all the calls to $fm->define(). What is this $fm variable within these definitions?

When I try to set up my tests like the examples in the docs, I just get errors because I'm trying to call a method on this undefined $fm. What is the proper way to set this up? It seems like the docs are making some sort of assumption that I am clearly missing.

GrahamCampbell commented 6 years ago

This $fm is a variable that is in-scope, because those files are required from a context where this variable is in the environment (informally, if you require a file in php, all global variables remain available to the file you require). A quick search on GitHub of the code for the word "require" took me here:

https://github.com/thephpleague/factory-muffin/blob/a8d6a6459cf2700acd0514610d745b0268fd1fa3/src/FactoryMuffin.php#L343-L363

This method is called by:

https://github.com/thephpleague/factory-muffin/blob/a8d6a6459cf2700acd0514610d745b0268fd1fa3/src/FactoryMuffin.php#L311-L341

flyingL123 commented 6 years ago

Oh wow. It was working the whole time. I was missing a closing parenthesis and blamed the package way too quickly. Thanks for making me take another look, and now I understand how it's working. I really appreciate your help!