Insert semicolons to PHP script automatically - php

I have some mental problem that prevents me from focusing on stuff that looks like PHP, what with the dollar signs and all, so my productivity whilst writing PHP is very low already. Having to remember to put semicolons at the end of statements is even more difficult, and if I forgot to do it a lot of times, going back and adding them one by one takes an immense amount of optical gymnastics.
So, is there any way, any tool, to add semicolons automatically to PHP scripts? Preferably a browser tool? I have tried searching on stackoverflow already. There is only one other question about the topic, wherein the only comment to that question tells the user to "Do it urself, it no hard"

Related

List or single line array/parameters: Does one or the other perform better?

A little bit of a generic question but it has been playing on my mind for a while.
Whilst learning php coding, to help me create a WordPress Theme from scratch, I have noticed that some arrays/parameters are kept to a single line whilst others are listed underneath one an other. Personally, I prefer listing the arrays underneath one and other as I feel this helps with readability and generally just looks tidier - Especially, if the array is long.
Does anyone know if listing arrays/parameters have any performance 'ill effects' such as slowing down the page load speed etc? As far as I can see, it is just a coder's preference. Is this a correct assumption?
Code formatting has no effect on performance.
Even if you claim that a larger file takes longer to read, if you are using at least PHP 5.5 then PHP will use an opcode cache - it will cache how it parsed your files for subsequent requests, eliminating any formatting that you have in your file.

Should a semicolon be included when building SQL query

When I access mysql from PHP (Joomla) application. Should I include semicolon in SQL queries I send? I.e.
$db->setQuery("SELECT * FROM `blah`;");
or
$db->setQuery("SELECT * FROM `blah`");
It might be a case of splitting hairs, but I want to do it consistently - might as well choose a way that is significantly or insignificantly better.
NOTE: Joomla platform code does not include semicolons in queries. But I don't trust it.
UPDATE: I understand that it works both with and without the semicolon, I am asking if there are any advantages of one way vs the other (except without semicolon being one character shorter).
Semicolons are primarily used to separate multiple queries when dealing with SQL, so no, you do not need to provide a semi-colon.
I am going to assume that the setQuery() function is storing these SQL statements individually in an array rather than creating a concatenated string which would run all at once so in this case you do not need semi-colons. You would probably break the matrix trying to run two SELECTs like that.
I can see semi-colons as becoming useful when you want to INSERT many rows into a DB and don't want to call execute() thousands of times but then again this syntax would work for that:
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
I have primarily used semi-colons when running a sequence of queries in the MySQL Workbench because the cursor needs to be somewhere inside the query you wish to run upon clicking that little execute lightning bolt thingy.
No Semicolons required just the queries will be working fine.

Identifying repeated code within PHP project

I have a single PHP file within a legacy project that is at least a few thousand lines long. It is predominantly separated up into a number of different conditional blocks by a switch statement with about 10 cases. Within each case there is what appears to be a very similar - if not exact duplicate - block of code. What methods are available for me identifying these blocks of code as being either the same - or close to the same - so I can abstract that code out and begin to refactor the entire file? I know this is possible in very manual terms (separate each case statement in the code into individual files and Diff) but i'm interested in what tools i could be using to speed this process up.
Thanks.
You can use phpcpd.
phpcpd is a Copy/Paste Detector (CPD) for PHP code. It scans a PHP project for duplicated code.
Further resources:
http://qualityassuranceinphpprojects.com/pages/tools.html
You can use phpunit PMD (Project Mess Detector) to detect duplicated blocks of code.
It also can compute the Cyclomatic complexity of your code.
Here is a screenshot of the pmd tab in phpuc:
See our PHP Clone Detector tool.
This finds both exact copies and near misses, in spite of reformatting, insertion/deletion of comments, replacement of variable names, addition/replacments of subblocks etc.
PHPCPD as far as I can tell finds only (token) sequences which are exactly the same. That misses a lot of clones, since the most common operation after copy-paste is edit-to-customize. So it would miss the very clones the OP is trying to find.
You could put the blocks in separate files and just run diff on them?
However, I think in the end you will need to go through everything manually anyway, since it sounds like this code requires a lot of refactoring, and even if there are differences you will probably need to evaluate whether this is intentional or a bug.

Documenting PHP Code - does it hurt performance? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I can't believe anyone would normally object to documentation and comments, but whats the best practice (and practical) for doing so in PHP?
In JavaScript, you can document your code and then run a minimizer to produce a production version of your code for use. What about in PHP, does the extra lines of text affect performance? Should you keep your documents in another file (which I imagine might be important for API's and frameworks but would slow down your development)?
Edit:
My logic was that it would necessarily take longer because the file size is longer and add more work (though possible negligible) for the parser to sort out. Say you had 1000 lines of code and 500 lines of comments, should you put a summarized version instead and then direct to actual documentation page?
With PHP (like ASP.NET) the code can be compiled on the server and HTML generated to be sent down the wire to the client.
PHP source code is compiled on-the-fly to an internal format that can be executed by the PHP engine. In order to speed up execution time and not have to compile the PHP source code every time the webpage is accessed, PHP scripts can also be deployed in executable format using a PHP compiler.
Source
During this process the comments are ignored and play no further part in proceedings. They don't slow down the compiler and hence don't affect performance.
You should comment your code (where appropriate) and keep the comments with the source code. Otherwise there's an even greater chance that they'll get out of step with the code and then worse than useless.
If you assume an O(1) CPU cost for every comment character, and your code is 4k, and half of the code is comments, then you waste 2k basic operations. With modern processors, a basic operation is ~ 20 clock cycles, but since there's pipeline optimizations, we can assume maybe 5 cycles per operation. Since we're dealing with gigahertz CPUs these days, 2k/1g * 5 ~= 1/10,000th of a second wasted on comment parsing.
Comment your code!
Negligible elements:
4k is one partition block, so disk reads are minimized. You'll have to go to disk anyway for the program code. CPUs have enough cache, so the whole program will be held in memory, comments and all.
Context switching events are likely to occur, but the amount of time executing PHP code is much greater than the amount of time ignoring comments.
The interpreter must maintain state, so any state-maintenance is not included in the processing time. Why? Because once we know we're in a comment, we just continue reading until we detect end of comment. All O(1) per character except when starting/ending a comment.
Setup/teardown execution of PHP is neglected because comment-detection would occur regardless of comments existing or not. The lack of comments in your code does not prevent the interpreter from attempting to detect comments. Therefore, no speedups to you.
Comment your code!
No. Does not affect performance, but it will affect your readability. A wise man once said "Comment as if the next guy to maintain your code is a homicidal maniac who knows where you live.”
Minimizing javascript is a good idea because the whole code is sent to the client - for code with a lot of comments or clients with slow connections, this could lead to a substantial delay in processing (where substantial could mean seconds..).
This is not the case with PHP - the code executes directly on the server and thus only the processed result is sent to the client. There may be some small overhead whilst the PHP preprocessor parses the code, but I would expect this to be negligable - a few milliseconds at most.
Adding documentation to your code will in no way impact your performance (neither negatively nor positively). Documenting your code is really important so other people (and yourself after a few months) can figure out what's going on. It may take perhaps one millisecond second longer for the lexer, but that's barely even worth mentioning.
It will increase your file size. But the parser ignores it, so it won't impact performance in terms of execution time, etc.
I think the general consensus is to comment within the actual code. While I suppose you could maintain separate files of documentations with references to your code, I can only imagine how cumbersome that would be to maintain.
Definitely, without question, document your PHP code .. it's already bad enough for someone trying to understand what you've done. Any detriment, and I cannot think of any, to documenting code is completely outweighed by the benefits
I am willing to bet that removing comments from almost any code results in zero noticeable speed improvement.
So the answer to your "best practice is": don't remove comments
The primary difference is that JavaScript has to be sent to the client, so those extra bytes take up resources during transfer. And it's not really important to send the documentation to the client. In PHP on the server side, those comments will be ignored by the parser. So document to your heart's content :)
the parser will ignore it. keep the documentation there and never skimp on it. the more comments the better.
When using docblocks for commenting your classes/functions/variables etc, it allows IDE's that support code suggestion/highlighting to give you information about the resuources that you are using as you write. Also, when it comes to creating documentation, there are various tools out there to automate this process using docblocks; in short, if you comment correctly then you already have created your documentation too.
In terms of efficiency, yes the parser will have to filter out comments when the file is loaded into memory (along with white-space I might add). However, this filtering process is run only once at the server and before the php script itself runs which itself will take considerably longer to run. This means that the proportion of time spent on the execution of the intended PHP will be much less comparatively and therefore any decrease in efficiency will be negligible.
Also, think of the time that you will save your successors; that is reason enough ;)

Realtime MySQL search results on an advanced search page

I'm a hobbyist, and started learning PHP last September solely to build a hobby website that I had always wished and dreamed another more competent person might make.
I enjoy programming, but I have little free time and enjoy a wide range of other interests and activities.
I feel learning PHP alone can probably allow me to create 98% of the desired features for my site, but that last 2% is awfully appealing:
The most powerful tool of the site is an advanced search page that picks through a 1000+ record game scenario database. Users can data-mine to tremendous depths - this advanced page has upwards of 50 different potential variables. It's designed to allow the hardcore user to search on almost any possible combination of data in our database and it works well. Those who aren't interested in wading through the sea of options may use the Basic Search, which is comprised of the most popular parts of the Advanced search.
Because the advanced search is so comprehensive, and because the database is rather small (less than 1,200 potential hits maximum), with each variable you choose to include the likelihood of getting any qualifying results at all drops dramatically.
In my fantasy land where I can wield AJAX as if it were Excalibur, my users would have a realtime Total Results counter in the corner of their screen as they used this page, which would automatically update its query structure and report how many results will be displayed with the addition of each variable. In this way it would be effortless to know just how many variables are enough, and when you've gone and added one that zeroes out the results set.
A somewhat similar implementation, at least visually, would be the Subtotal sidebar when building a new custom computer on IBuyPower.com
For those of you actually still reading this, my question is really rather simple:
Given the time & ability constraints outlined above, would I be able to learn just enough AJAX (or whatever) needed to pull this one feature off without too much trouble? would I be able to more or less drop-in a pre-written code snippet and tweak to fit? or should I consider opening my code up to a trusted & capable individual in the future for this implementation? (assuming I can find one...)
Thank you.
This is a great project for a beginner to tackle.
First I'd say look into using a library like jquery (jquery.com). It will simplify the javascript part of this and the manual is very good.
What you're looking to do can be broken down into a few steps:
The user changes a field on the
advanced search page.
The user's
browser collects all the field
values and sends them back to the
server.
The server performs a
search with the values and returns
the number of results
The user's
browser receives the number of
results and updates the display.
Now for implementation details:
This can be accomplished with javascript events such as onchange and onfocus.
You could collect the field values into a javascript object, serialize the object to json and send it using ajax to a php page on your server.
The server page (in php) will read the json object and use the data to search, then send back the result as markup or text.
You can then display the result directly in the browser.
This may seem like a lot to take in but you can break each step down further and learn about the details bit by bit.
Hard to answer your question without knowing your level of expertise, but check out this short description of AJAX: http://blog.coderlab.us/rasmus-30-second-ajax-tutorial
If this makes some sense then your feature may be within reach "without too much trouble". If it seems impenetrable, then probably not.

Categories