I don’t know about you, but sometimes things that are right in front of me are invisible. DIY jobs, washing up, … you get the idea :-)
It’s the same in IT; whilst waiting for a new Laravel project to be created (on Windows), I noticed this line and thought it was worth talking about because there might be aspects of it that other’s may be unaware of.
@php -r "file_exists('.env') || copy('.env.example', '.env');"
So what does it do? It’s obviously referring to the .env files but how? To understand, let’s break this line down bit by bit.
This prevents the command from echoing itself onto the screen.
This allows you to run PHP commands without the script tags - basically, it let’s you directly execute functions etc.
No prizes for guessing this. Does a file or directory exist? It returns
TRUE if it does, and
Again, nothing spectacularly complex here. This also returns a boolean:
TRUE if the copy worked and
file_exists('env') || copy('.env.example', '.env')
Right, this is really the whole point of this blog entry - the interesting part. This works by taking advantage of something called short-circuiting. You can find out more about it here but put simply, PHP (like most programming languages) will be quite lazy about evaluating things.
In this case, if the first expression evaluates to
TRUE, it doesn’t bother evaluating the second. In this case, that means that if the file is there (i.e. it exists), it doesn’t need or try to copy the
.env.example file to it. If it isn’t there, it does copy it!
Pretty cool, right?
Hi! Did you find this useful or interesting? I have an email list coming soon, but in the meantime, if you ready anything you fancy chatting about, I would love to hear from you. You can contact me here or at stephen ‘at’ logicalmoon.com