Each form has advantages and disadvantages.
Text file
At the time when I was developing a framework in PHP, I thought a lot about the possibility of storing queries in text files.
This would reinforce the separation of concepts, that is, I did not want to worry about the syntax of PHP mixed with SQL.
However, after considering the impact of reading and processing the files, I gave up the idea.
Separate PHP file
I used this approach in a project and found it very interesting. Each class had a PHP file with queries in strings. heredoc
is an interesting representation of this approach.
The advantage is that you can get an overview of queries , making SQL refactoring easier, and your code gets cleaner. The downside is that sometimes you need to keep switching files multiple times to see the contents of the variables.
Queries inline
Today I avoid to the utmost, in any language put the queries directly inside a function or method.
First because with SQLs distributed in the middle of the code, if the table changes, I often forget to update one of the "lost" queries in files and methods.
Second, because although it works well for queries very simple, it usually ends up "spoiling" the formatting of the code and "breaking" the flow of the code, disrupting its reading.
Representing SQL in String
To represent SQL in a PHP String, I would avoid to the maximum the way it concatenates line by line. This is asking for a tendinitis.
Using multi-line quotes, it does not look so ugly if you do not use tabs. Example:
<?php
$sql = "
SELECT *
FROM usuarios u
ORDER BY u.nome";
The only problem of the above String is a line break at the beginning.
The heredoc
format seems to me to be the most interesting. First because there is no problem with the line break or formatting. Also, it allows you to copy and paste the query easily, which I consider important, since I do this frequently during development.
Once you get used to it a bit will not seem so strange. ;)
On the other hand, as mentioned in the question itself, there is still the Nowdoc
format. According to the documentation, it works as single quotation marks, where the content is not parsed and therefore variables are not interpolated. The use of Nowdoc
is interesting because it avoids unnecessary processing on "constant" strings, that is, it does not have PHP variables inside.
General considerations
Adopting a pattern where to store queries facilitates developers' understanding of the system and avoids the introduction of bugs , as there are no SQLs sprinkled by the code. p>