Is GOTO in PHP evil? [closed] - php

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 9 years ago.
Improve this question
I recently found out that PHP 5.3 supports new language construct called GOTO. Everybody knows what it does. However, it's not exactly the traditional GOTO, it's just a jump label. I'm interesting in knowing whether this GOTO is evil and implies bad code?

Unless you are programming in assembler, GOTO should always be treated the same way as the life vest of the airplanes: it is good to have them available, but if you need to use them it means that you are in big trouble.

I can't believe nobody posted this :)
Granted, PHP is not compiled... Maybe the raptor will chase you on every visit to your website?

Bad structuring of code is evil, regardless the control structure you use.
I personally prefer a goto that makes clear the flow of the program to "control variables" and nested "if" that will indirectly just cause the same branch in the code.
So, just write the two versions (with and without GOTO) and see which one it's easier to comprehend. Then the choice is easy.

I think this is the most important part of the PHP manual page and missing here:
This is not a full unrestricted goto. The target label must be within the same file and context, meaning that you cannot jump out of a function or method, nor can you jump into one. You also cannot jump into any sort of loop or switch structure. You may jump out of these, and a common use is to use a goto in place of a multi-level break.
IMHO this makes it very different from the ye olde BASIC style gotos.

I'm in the minority (currently), but I believe the restrictions placed on PHP's goto construct make a very beneficial tool:
http://adamjonrichardson.com/2012/02/06/long-live-the-goto-statement/
I actually walk through an example of arrow code (deeply nested conditionals) and refactor it using standard practices (guard clauses, grouping conditions, pulling out functions) in one version and a goto-based version in the other version, and I actually prefer the goto-based refactoring.

Are guns evil? Both can be used for good or for evil. I would say it was easier to write good code without goto, than with.

Any language feature that can make code more readable in a given situation is A Good Thing. GOTO is one such language feature, even if those situations are few and far between. If we forbade any syntax that made it possible for poor programmers to write bad, unmaintainable code our jobs would be an awful lot harder.

As a software engineer, i mostly work on "mainframes" and "big corporate servers"...
And our daily language (I mean the one in 95% of our base code) is Cobol, which uses extensively GOTOs.
This usage doesn't mean the code is bad. It just means that this tool (GOTO) was the right one at the moment programs were written.
To answer Kaitsuli's question, I think it can be useful tool when writing PHP scripts.
On the other hand, a lot of scripts were achieved without it for almost a decade by now. Furthermore, it goes against PHP's evolution with more object-oriented features.
IMHO, it's nor good nor a bad thing for the code be produced : good programs will still be good and "horror programs" will be worse... The only question is : "Why adding GOTOs 10 years after proving it was not necessary ?".

GOTO usually is evil because it lets you build unstructured code. With the usual loops you can build good structured code easy to follow because it is structured.
When you have non structured code jumping from here to there, you have just found the evil coming from the GOTO statement. Almost always is better to avoid it. Maybe once every 100.000 lines there is a place where a GOTO sentence simplifies A LOT the code thus is not evil but if you are unsure, then you should avoid the GOTO.
Hope this helps.
EDIT: Well, just to add my own opinion here, there are other instructions that allow you to create unstructured code and that are not considered evil when I think they should be.
For example a return in middle of a function is a GOTO to the end of it so I avoid them and use only one return in each function just at its end.
Other languages like Vb.Net (maybe others too) allow to do Exit For, Exit While, breaks and things like these that also unstructure the code and I think should be avoid.

sometimes (I mean in 0.01% of cases) it is useful, like when you have a long long script and you want to test some blocks. but never keep it in your final script

I used GOTO when I write script for working under cli mode. It save my life.

Related

PHP Practices for first time web-programmer [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have this idea for a website that's been floating around my head for quite sometime now and now have finally decided to get to work on it. Due to the nature of the project and my experience I am getting comfortable with the idea of running it as a PHP+MySQL application on an Apache server.
This is my first time doing web programming of any sort(I have a background in sysadmin and mainframe systems coding) and I am pretty unsure of what practices to take into consideration so that I don't find myself undoing/redoing things later in the project. Considering all the flak the language has taken on StackOverflow(which can be seen here and here) it would be nice to have a set of common mistakes to watch out for for a beginner like me. I did find this thread outlining things to avoid in PHP but most of the points made little sense to someone like me who's just setting out in PHP.
Do you have any suggestions, tips or tutorials outlining common gotcha's in the language which might come back later in the project demanding entire rewrites.
For what it's worth I am currently working my way through Programming PHP(O'Reilly) and PHP in Action(Manning).
I was in a very similar position a couple years ago, having come from a NOS background myself.
I actually started with PHP and MySQL for dummies. Once I had absorbed the knowledge contained therein, I hit the Web (I used SitePoint a lot, like Boushley recommended) and I read a couple of O'Reilley's book on the subject.
Once thing I will tell you, is that if you want to streamline your understanding and your efficiency, I have found great success with a number of MVC frameworks(CodeIgnitor, CakePHP, etc). If you have no idea what MVC is, I recommend finding out. Now that I use MVC, my code is easier to understand, modify, troubleshoot, etc.
And honestly, half of the learning in PHP is running into those common mistakes and learning from them. Its hard to appreciate those 'common mistakes' until you make them.
Don't worry about HOW you are going to learn, just START leaning!
If I could give you one piece of advice, it'd be to use a framework - they will make your life so much easier. They take away all the repetitive code from programming websites, handle security concerns and abstract lots of things, as well as make you build your website using a pattern such as Model-View-Controller.
I highly recommend the CodeIgniter framework for it's simplicity, power, great documentation and ease of use, but there are plenty of other good frameworks too. There are lots of questions on SO on this so have a quick search. There is a fantastic introductory screencast on CodeIgniter (soon to be a series) from BinaryCake, so check that out here.
I hope that's helped! If you have any PHP concerns, feel free to message me - it's my area of expertise (along with CodeIgniter) and I love it!
While still developing, have all errors show up:
ini_set('display_errors', '1');
error_reporting(E_ALL | E_STRICT);
Can save a lot of time (in case of say, typos in variable names). Change this when it goes live to not display or only display "real" errors depending on the type of site and security levels involved (you don't want everyone to know paths and variable names and such..).
Find a variable/function naming convention (under_scores vs camelCase vs..) that suits you and stick to it. Also, classes go in the /class directory, includes in /inc etc. Both these make it easier to understand your own code years from now. Oh, and the same goes for coding style, I guess: choose one and stick to it (indentation, bracket style, ..).
Comment your code :-) Personally I also have a little log at the end of longer files that shows when I did what and why. Each addition is timestamped, and the same timestamp is also in the comments behind the change itself, as the line number on which it sits can easily change. Similarly, in an included file containing a bunch of functions, I have the list of function names in a comment at the top of the file, with a one-line description behind them.
Finally on security (though this should really be your first concern ;-) ), treat all user input as suspect. That's POST & GET data, cookies, user-agent string, search strings - anything that is supplied by the browser. It's trivial to change cookie data or change/add form items.
Read up on SQL injection & XSS attacks, and look at PHP's relatively new data filter functions: http://php.net/manual/en/intro.filter.php
Google any of these to get some good reading
Don't use register_globals
Turn off magic_quotes - escape all user entered input in SQL statements
Escape any user entered input printed with htmlspecialchars()
Plus a lot more... These are some common things to watch out for though.
There are a number of great websites out there with lots of tutorials. One that comes to mind is Site Point. They'll try their best to sell you a book or two while your're there, but they do have some decent articles. This article for instance discusses some common security blunders in php.
http://www.sitepoint.com/article/php-security-blunders/
They have lots of them...
http://www.sitepoint.com/search/search.php?ps=10&q=php&submit=Search
Also a nettuts.com has a load of tutorials an things of that nature. They're more all across the board though.
http://nettuts.com/
And I think pretty much everywhere you look you'll see the common ones like watch out for register_globals, magic_quotes...
one good book to look at that is also free to download here covers beginner to advanced PHP techniques and is good way to learn good standards :)
Use a framework and use Object Oriented Programming
Books are great for learning additional languages, but for your first one, a good video tutorial is a great way to go!
Register for a Lynda.com account (google: lynda trial) and sign up for as many one day trials as you need (or be a good honest person and purchase a week). They have a pretty good beginner and advanced PHP series of video tutorials which are (IMHO) a great way to learn your first language.
A tip: If you can start programming Object Orientedly from the get-go, you will save some time in the future and learn good practice from the start, luckily the advanced tutorials cover this!
Here's a link: http://www.lynda.com/home/DisplayCourse.aspx?lpk2=435
I've never taken this particular course (when I learned a few years ago, it was different), but I just recommended this to a friend (who was just starting), and he really liked it!
Hope this helps!
If you're new to programming in general, A database backed web application is likely to be a bumpy ride. You will probably be programming in at least two, real programming languages, PHP and SQL, and if you're going to do anything of modest complexity, JavaScript too. Keeping them strait will be rough, because they are all quite different.
Just to warm up to programming, you might want to start instead using a more focused learning excercies, such as working through the Euler Project problems, or Code Kata.
Either way, Try to pick up good habits wherever you learn about them, including the popular suggestion here of using an MVC framework for the heavy lifting.

Is this interview question too hard for a php dev. job? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
We're looking for someone to help us enhance & maintain our high-quality, php-based prototype of a transactional web app. Ideally, who can communicate well, and do both front- and back-end web development (as well as smart/gets things done, etc.). Among other more general things, I've been using this question:
Given this:
$foo = array(1, 3, 7);
write a function (on this whiteboard) to sum the values of the array.
It seems trivially easy to me, but has caused a couple of deer-in-the-headlights situations, which always makes me feel like a villain.
I've read a number of posts here and there (including both Joel's and Jeff's) saying that how candidates think, design skills, passion, etc. are more important than any specific technical skill, and I agree with that. Also, I can see that programming at a whiteboard is a little unrealistic. OTOH, this seems so basic to me that I'm inclined to see it as a fine first-pass filter between front-end devs (who know their way around html, css, and how to copy-and-paste a js function or two), and people who can really code. Thoughts?
A touch more info: I'm open to all sorts of answers: array_sum, a for loop, a foreach loop. Heck, if they want to write an ArraySum class, that would be overkill, but just fine. Using javascript, or another language would be fine, if they're more comfortable with that. Even attempts with minor errors would be ok, but I've had a couple of complete freezes, so I just wanted to sanity check myself.
I would consider that much too easy of a question, personally. If someone asked me that question in an interview I'd probably be busy trying to figure out what the "trick" was, because it's so simple.
I think it's fine for weeding out the absolute worst programmers, but make sure that you don't have one particular "right" answer in mind and refuse to accept anything else. For example, don't only accept "use the array_sum() function" as the correct answer, where it's really just a test to see if they know the function exists.
I mention this because my fiancee once had a programming interview where she was asked how she would reverse a string. She gave several different algorithms that would accomplish it, with the interviewer telling her that she was wrong after each one. She finally gave up, and he (disapprovingly) told her that she should have just used the String.Reverse() function.
Don't do that. Please.
in my opinion, the question is perfectly valid, and tells a bit (not a lot, but an important bit) about the candidate, depending on how much time you invest in it. just tell her that it's not a trick question beforehand, that it's really, really as simple as it appears, so she doesn't spend to much time thinking about the pitfalls and to minimize the deer-situation. throw in you do that just as a measure to filter out the people who apply for a programming without actually knowing anything about it but hoping they get hired anyway by pure luck (if they know how to code but are just nervous, that should take a bit of pressure away). let them code, but don't focus if there is a $ missing or if the <?php tags are present or not.
if she provides array_sum or sum_array as an answer almost doesn't matter, especially if the language in question is php (but if two candidates are equal otherwise ... i can't even remember the last time i had to use this function). and the use of an auto-completion and syntax-coloring (with predefined keywords) IDE vs. a dumb text editor matters a lot in this hindsight. in this case ask for an alternate, handcrafted solution.
if i was in the position of asking that question i wouldn't ask for the right solution, i'd ask for ways that come to her mind how this problem could be solved, what pitfalls could arise in special cases. try to find out what she knows about programming, not what she knows about php. try to find out about intelligence, problem solving and creativity. altought experience matters a lot even when it comes to bang out code fast, it's not a constant.
the solutions i'd provide, the pros/cons and what it tells about me ...
built-in array_sum (very fast and definitley not buggy, but inflexible): i have a bit of experience with traditional php projects
for/loop constructs (good enough, reinventing the wheel. but can be used if there are different objects than numbers. pros: everybody will understand it): i can solve simple problems if there are no predefined copy&pasteable solutions
array_reduce (with an offering to implementat array_reduce, if the interviewer wants to see it): unusual for a php programmer, so it seems i have knowledge and experience outside of the php sandbox
an ArraySum-Object (with an ArraySum::add($value) method that keeps all values stored but caches the sum): i'm used to at least some of the oop-principles
function () { return 11; } (with the disclaimer that this is a joke solution, but valid): i have (albeit crude) programmer-specific humour - a sign i'm personally interested in programming outside of work ... some interviewers who are programmers (but not hackers) might interpret this as a willingness to use dirty hacks as placeholders (aehm) if time constraints are too tight
a recursive solution would be nice. i can probably solve a bit more complex, algorithily problems too and most likley know my way around simple trees and data structures
recursive divide and conquer: bonus! i know even more about algorithms.
try to get as much as possible out of this question (if time permits). in the end you'll know a little bit about programming capability and a lot about experience (altought not necessarily PHP specific).
i'd choose this question over letting the candidate write out quicksort - a very specific question about knowledge almost never needed in the web dev world - any time.
disclaimer
the question is useless when ...
the interviewer is not a programmer. forget it if a hr-guy is doing it
there's a very tight time constraint when interviewing. then the result is almost random anyway.
additionally, who are you looking for? if you need a cheap grunt coder, even a simple question like this should work. if you need quality and experience, don't waste too much time on it (but do it anyway).
No, it isn't too hard. If someone doesn't understand the concept of a loop or how to iterate through an array, they're not qualified as programmers. I'd also want them to know that there's a built-in function for that (array_sum()), or at least where to look for it.
You might want to take a look at The Five Essential Phone-Screening Questions, although you'll probably have to rework them a bit to suit your needs.
My own view is that there is a limit to the kind of toy questions you could ask for programming on a whiteboard. At best, these are simply toys that are often circulated on online forums and your candidates will memorize.
Most PHP developers created visible websites - you could see their work.
To me, a much better question would be to give him a complicated piece of your own production code and have him explain what it does or how it can be improved, etc. Most of the time will be spent doing maintenance anyway, better get an idea on his code reading skill, not just code writing.
Short Answer: No
Edit: Just to clarify I don't think this is a hard question at all. Regardless of the language. As others have posted, even if they can't get the syntax correct, the should at least be able to write it out in a reasonable pseudocode.
Long Answer:
I often ask interview questions I expect the candidate to miss. One could classify them as too (hard|vague|open-ended), but I am not really looking for an answer. I am looking to see the following:
Do they try to answer the question? Some people just give up immediately
How do they approach the problem? Even if they go down the wrong path are they generally making good assumptions and asking good questions?
How well do they maintain composure under stress? The question is designed to be hard, and therefore will be stressful. Do they panic, remain calm, withdraw, talk it out, etc...?
Are they able to find the solution if I give them hints and pointers? Or how well do they listen, and do they assimilate new information quickly?
Occasionally I am surprised with a candidate who is whip-smart, and just codes up a quick and elegant solution. Those are definite keepers. But I also find good candidates by people who miss the final solution, but are clearly thoughtful, logical, and given enough time would eventually solve the problem.
no, it isn't too hard, but it may cause people to panic if they do not exactly remember the syntax (though if you specifically ask for a php dev, then they should at least remember some syntax). Ask for pseudocode instead, if they still cannot do the question then there is a problem :)
If your applicant can't write a simple for loop and some addition on a whiteboard, you absolutely don't want them touching your code. Even as a front-end developer, they'll be using for loops all the time to output lists, table rows, image galleries and the like.
This is the type of basic thing you ask on the phone before bothering to bring a candidate in house.
There are a couple of standard things I ask every programmer about: Do a select on two tables to give a sum of a column in the second table, delete records from one table based on values in a second, difference between an object and a string as a method parameter, and a couple of html/css related questions.
Within 5 questions I can weed out 90% of the candidates before I even see them. The rest of it is going to boil down ideology.
My favorite would be:
while ($foo && $sum += array_shift($foo)) continue;
This question may be better improved by providing the documentation for the array() function, because if they don't know what it is, they could very easily look it up themselves in a job.
It's not too hard. If they cannot answer that question, they obviously cannot code their way out of a wet paper bag. I would definitely not hire such a person for any kind of development work.
Question is, how could you improve your recruiting process to avoid interviewing these candidates in the first place? Sounds to me like you're not screening your applicants enough before inviting them in for a chat.
If you can't write code to sum an array (in whatever language you prefer) I don't know what you can write. What on earth do you think someone could contribute to your project if they can't write code to do that question?
Actually, this questions seems kind of... easy.
I suppose writing it on a whiteboard makes it more difficult, though.
This question should be easy for people that have programming experience, but I'm guessing you may be getting a lot of designers that picked up PHP by copying/pasting code snippets in place.
Maybe you need to update your job listings to make them more programming centric and avoid web design terms.
No, it's not hard. What you've discovered is that there are a lot of "programmers" out there who can't program - they can memorize, they can copy and paste, but they don't actually understand what they are creating (in most cases they seem totally unaware of their lack of understanding).
This lack of understanding becomes painfully obvious when they are asked to write something simple from scratch - writing just the glue code, without all the complex stuff that they'd normally just grab as code snippets and then shift around until the compiler stops complaining.
In general you want to avoid these people like the plague, as they will consistently produce buggy code and will not understand why you or your customers think it doesn't work.
Jeff wrote about this a few years ago: Why Can't Programmers.. Program?
To be honest, I would like to think that if a person applies to a programming position, he or she will probably have the relevant skills on their resumes. Why not ask simple problem solving questions instead if the position doesn't require some sort special skills in the language in question? I was once asked how many pizza stores there are in my country. They were interested in checking how I approached the problem and weren't really interested in how awesome I might be in the relevant programming language. I think that was a good way to go about it. Am I awfully wrong in thinking that?
Edit: Or is it very common that people fake their resumes?
(I think the array_sum($array) method, as part of PHP, will do the job.)
The question really is trivial. Although there is enough space for error in a stressful situation but summing up an array should be easy enough for anyone with basic programming skills in any language.
It would take a dunce to muck up an interview with a question like this. The question is not too hard, it's actually very lenient.
It depends on what you're trying to ask. Are you screening their ability to recall syntax? Or are you looking for best-practice methods in dealing with array functions? If it's the first case, your question is fine.
On the other hand, if you're trying to see how well a person actually understands code, and knows implications based on how something is structured, the question is good, but instead of requiring them to write a line by line function, invite a discussion on how they would do it, and what would be some considerations with their answer. Why not do it via method B?
IME, asking for rote memory responses (syntax recall, port numbers, etc etc) tells you some aspects of an individuals ability, and sometimes need to be asked. But more important is digging into their problem solving abilities.
I don't see why anyone would have any problems with that. (Assuming that they are developers) And yes, programming at the whiteboard is unrealistic but that is a trivial question which any developer should be able to solve.
I had a deer-in-the-headlights moment wondering what the trick was!
Anyone applying for a programming job will know how to add integers together (one way or another, even if it's in a loop), so I'd skip it and find something more challenging....but not so confusing! :)
I've done interview recently for PHP position. I've been asked to write simple function on paper (of course not as simple as your example).
Anyway, when I've done that function (some 6 lines of Python code), interviewers where
pleased. They told me, that there are lot of ppl unable to write any code without IDE, and this small test serves to filter them out.
As for your example — it's just to simple. Especially if you accept array_sum() as an answer.
I wouldn't believe that there are such "programmers" out there, if you'd asked me a few years ago. But what has been seen cannot be unseen. I've witnessed firsthand people who make a living out of programming websites and know nothing about programming. They just copy and paste other people's code around, until they get it running. And you wouldn't possibly believe how their income level fares compared to their "skills" (yeah, income level does not directly relate to skills but it still freaks me out).
Yes, you are sane and those people do exist. And what you are doing is one of the useful filters for filtering "pragmatist script copy-pasters" (or others) from real coders. Of course, unless you want copy-pasters (they can accomplish some simple tasks! -or more complex ones but with unbelievable code-) in which case such an interview question is really hard for them.

What are the PHP-specific antipatterns that you know of? [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
PHP as a Blunt Instrument
I hear PHP getting bashed around a lot lately. In quite a few projects, I have seen insane php code bases - so bad you really wonder if the person was on hallucinogenic drugs when they wrote the code. Sometimes, I wonder what the code would have been like if the initial developers had a bit more guidance as to what not to do.
However, I have also seen some very well organized PHP projects that were done in 100% OOP and were a pleasure to maintain, but they were not written by "php programmers."
I give all of our junior devs a link to Java Anti-Patterns. One of the nice things about that page is the Java-specific examples because there are many features of Java that lend themselves to common mistakes. I was hoping to find a similar list for php, but a google search did not reveal anything meaningful.
There are a few questions already out there for what a developer should know when programming PHP, but I wanted to focus on the negative.
What are the common things you have seen in PHP that should be avoided and what is a common solution to doing the same thing in a better way?
Some of the obvious examples to me that I think will be mentioned but aren't PHP specific:
Don't concatenate SQL. Use prepare statements or proper escaping.
Don't blindly embed PHP into HTML - use templating/MVC.
Don't blindly post raw unfiltered user input - scrub it for XSS attacks.
Don't manually try to parse all of your POSTs and GETs - use a web framework.
Here would be some examples that I would consider PHP specific:
Don't have too many layers of file include/require linking and try to avoid conditional linking. Rather, have a sane naming convention and be consistent with your organization.
Don't use PHPs raw database API unless you can help it, instead use a database framework like ADODB instead.
Don't overuse PHP's dynamic typing by setting the variable to a string in one place and a boolean somewhere else, then expecting the boolean tests to make sense.
So, what are your favorite PHP don'ts and how do you do it right?
I disagree with this one:
Don't blindly embed PHP into HTML - use templating/MVC.
PHP is a templating language. While I agree with the concept of implementing MVC, I don't see why there should be a requirement to implement a yet another DSL around producing web output.
Adding closing "?>" tags to the end of php files can lead to accidentally pushing white-spaces to the output buffer. The PHP interpreter will automatically add closing tags to files, and doing it manually is somewhat of an anti-pattern.
Never EVER use a $_GET or $_POST without checking it and cleaning it up.
Read about how to set up the php.ini right.
Never put variables into raw SQL.
If you use frameworks, use the ones with less dependencies.
Stop over-generalization.
Distribute your code on the php files. In most cases there is no real need to put everything into one index.php.
Reduce complexity before writing code.
Respect the fact that it is a web application. (Try to be RESTful.) It's not a desktop application. So stop putting everything into $_SESSION.
At least one comment line for every 10 lines of code. You WILL read that after a year. I promise!
Code like a girl - make it nice to read.
My current pet peeve is inconsistent-return-type for query-functions. This is when you call a function to execute a query, and it returns
NULL or FALSE or something similar when no match is found
The matching object/value when a single match is found
array of matching objects/values when more than one match was found
which forces you to check the return types and deal with each case specifically. It would be much better to simply always return an array with 0, 1 or n elements.
One of my favourite DON'Ts would have to be:
$query = 'select * from users where username = ' . $_POST['username'];
Can it get much scarier than that?
If I had to include a favourite don't it has to be the one posted by karim79:
$query = 'select * from users where username = ' . $_POST['username'];
Many developers in PHP keep stuck in structured age. PHP supports classes and objects since a while ago, I just don't get why people keep hard coding PHP into html, without templates or nothing at all.
I believe that developers from other languages, like .NET or Java have earned the right to criticize the language if so many developers keep programming like that. PHP is a very great language, very flexible, still a little junior but is growing, but many just don't get it, all they want is to solve by making the old classic copy & paste.
use SPL
use PDO instead of using mysql_query or pg_query or others
always use the filter extension on user input

What should every PHP programmer know? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Closed 8 years ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
I would like to be a PHP/MySQL programmer
What are the technologies that I must know?
Like:
Frameworks
IDEs
Template Engines
Ajax and CSS Frameworks
Please tell me the minimum requirements that I must know, and tell me your favourite things in the previous list?
Thanks
First off, there is no must know about learning PHP and MySQL... You go into it not knowing anything, and you'll come out of it knowing a bunch. If there was a must know, then nobody would be able to get into PHP and MySQL development. I personally think you are at a slight advantage going into this without knowing everything about it. It'll give you a fresh perspective and a think outside of the box attitude :)
As far as the object oriented stuff in this thread, it's true. But, as others have said, it's completely up to the programmer (you) to decide how to write your code. You can use object oriented practices, make a spaghetti code junction, or just right a bunch of functions, or whatever. Either way, as everyone else has been saying, it's up to you :)
IRC channel:
Don't really need this, but I find it helpful... See you in here :)
irc.freenode.net #php
Manual:
The manual is your friend and probably the only thing you should know before diving in.
http://www.php.net/manual/en/
http://dev.mysql.com/doc/refman/5.0/en/apis-php.html
Frameworks:
Make sure it's an MVC framework :)
http://www.cakephp.org/
http://www.phpmvc.net/
http://www.codeigniter.com/
http://www.symfony.com/
http://www.laravel.com
http://www.yiiframework.com/
IDE:
Whatever suits you best :)
http://www.eclipse.org/
http://www.vim.org/
http://www.zend.com/en/products/studio/
http://php.netbeans.org/
https://www.jetbrains.com/phpstorm/
Template engines:
PHP is a good template engine
Model view controller frameworks help with this
twig.sensiolabs.org
http://www.smarty.net/
Ajax:
http://jquery.com/
http://www.mootools.net/
http://developer.yahoo.com/yui/
http://www.prototypejs.org/
http://www.extjs.com/
http://code.google.com/webtoolkit/
https://angularjs.org/
CSS:
http://www.yaml.de/en/home.html
http://code.google.com/p/blueprintcss/
http://developer.yahoo.com/yui/reset/
Definitely not an exhaustive list, and things change constantly... But, it's a start :)
Have fun!
Chrelad
Security is an important topic every web programmer should study before being allowed to post code that can be accessed publicly on the internet.
Examples of security issues:
Injection flaws
Cross-site scripting flaws
Cross-site request forgery
There are more security issues that you should know and keep in mind as you write PHP applications. The website http://www.owasp.org contains lots of useful information to help.
PHP was my first language, which I learned on the side while working as an office junior in my first job over 10 years ago. Here is some things from my experience:
Download the PHP manual, print it off, and start reading from page one. Keep going till you're at the end. Skim over the bits you probably won't need (like using KADM5 or Hyperwave) but always read the introductions so you know what PHP is capable of (this will save you trying to re-invent the wheel). The PHP documentation blows the docs of pretty-much every other language I've worked with since out of the water.
Next step; set up PHP. Manually. Don't use XAMPP or anything else, do it yourself. It always helps to know how your environment is set up.
Don't bother with an IDE at the beginning. Getting to know a language means getting up-close-and-personal. IDEs obscure things in an attempt to help you GetThingsDone which works great when you know what you're doing and know your target environment, but when you're starting out they just get in the way and hide what's important.
Don't bother with frameworks at the beginning, either. Again, they're there to help you GetThingsDone which only works when you know what you're doing in the first place. Start with the basics, otherwise you'll be learning the framework and not PHP.
PHP is essentially an advanced templating engine. Don't fall into the trap of over-hyped "PHP templating engines". They're just doing what PHP already does, doubling-up on the work and running twice as slow as PHP does. Stick with inline html/php to start with. Again, this'll help you get to understand what PHP is, how it works, and when to use it.
As with AJAX and CSS... they're nothing to do with PHP, but with the output you produce from PHP (and with AJAX getting input in). Don't load your plate with too much to eat at once. Start with plain PHP+HTML, and do your CSS by hand. Then, when you're happy, mix in a little javascript.
The best thing you can do with any language is learn the environment you're going to be working in, because programming is (relatively) similar across all of them. They all have loops, data structures, input/output, etc, but they all work just that little differently.
Don't believe the hype. I'm moving from PHP to Python at the moment and I could've just jumped on the Django band-wagon to GetThingsDone, but I know that if I came across a problem I wouldn't know where to begin to fix it. So I'm taking my own advice and starting from the beginning; reading the manual, setting up an test system, parsing simple files, getting input/output, getting it linked in with a web server... all part of getting to know my new environment.
What should every PHP programmer know ?
You need to know a language that is not PHP. I'm not saying you shouldn't develop your sites in PHP, it's actually really good for that, but you really need to know at least one other language to get some perspective.
Why? PHP is broken and full of bad design and misfeatures. You can write excellent code in PHP, but you're never going to be able to spot the bad design and failures of PHP itself if you don't know any better.
I'd suggest python, ruby, or C#
PS: If you don't think this is a helpful suggestion, then by all means downmod this answer, but if you are downmodding because you feel insulted by my claim that PHP is broken and badly designed, don't shoot the messenger, I'm just telling the truth!
First of all, that PHP itself IS a templating system
Security.
Just like Lucas Oman said - it is up to you in PHP to write the code well; and it does not coddle you. If you don't understand why you need to confirm a logout, or why you can't just validate in javascript, or why register_globals is bad - your app will be vulnerable in some form or another.
You need to learn the following (I would suggest in this order):
Basic Object-Oriented Principles (such as inheritance, polymorphism, and encapsulation)
The PHP language itself. Specifically, PHP 5.
Database Design Principles such as tables, keys, relationships, normalization, etc.
SQL - Structured (or Standard never can remember which) Query Language. Specifically learn the basics of select, insert, update, and delete queries.
Good design principles and coding practices (you can find posts here on StackOverflow for one) such as dividing presentation and business logic.
A Framework, Any Framework - this will help you become introduced to more advanced concepts of object-oriented design patterns and allow you to follow tutorials that will encourage good design and coding practices.
Object-Oriented Design Patterns like MVC, Database Abstraction Models and the like
Advanced SQL and other database stuff like triggers, stored procedures, and other functions.
Ignore the mysql_* functions. Not only do they provide no straightforward method of writing secure code, they actually go out of their way to make it painful and tedious if you try. Use mysqli or PDO instead (and you've got no excuse now - PHP 4 was end-of-life'd months ago).
All good answers, but there is something important missing: If you want to seriously get into PHP, then you should be aware that there are a lot of PHP programmers out there who are lazy, inept, ignorant, misguided and unfortunately get their code released to the public. The history of PHP means that it supports some questionable features (not just things like register_globals but also smaller things like automatic initialization) and people still use them. You don't want to.
I would say the most important thing is to learn how the whole process of building a page with PHP works - in that requests come from a client (web browser), hit the web server, get passed through to PHP, which then generates the response that is sent back. A solid understanding of this will ground you in
why you can't send headers after output has started
how sessions and cookies work
how each page should be built in a stateless manner (i.e. deliver whatever the request asks for, don't remember what happened last time, or guess what the user is doing)
The difference between HTML, PHP, JavaScript and CSS, and more importantly, what each is used for primarily and where the responsibility of each lies.
Once you've got that down, then you should be quite comfortable with writing any app. But unless you've got that down, you'll start mixing things as I've seen many rookies do before now.
That every value everywhere has to be encoded appropriately. echo $some_variable_that_seems_innocent is evil nine times out of ten.
Use htmlspecialchars() in HTML/XML, prepared statements or at least addslashes() when building SQL queries, json_encode() when inserting values into scripts, rawurlencode() when appending URL components, escapeshellargs() when constructing shell commands, etc.
If you insert text in URL that's part of a script in XHTML document, you'll need to encode data three times.
Although this isn't a technology, I think it's very important that you understand that, when using PHP, it is completely on you to write good code. PHP is capable of it, but it does not encourage it. You are completely responsible for writing code that is well designed and, if you choose, follows OO principles. You will have no help from the language.
Use a great IDE (like Eclipse for example) that let you debug and have some code completion. This will save you some time.
PHP have a lot of programmer and is very popular = a lot of thing is already done for you, before writing some code, doing a google search is always a good idea.
You should use some of the Framework if you start from scratch. This will answer all your question about AJax, template engines... because most of them come with these packages.
Here is some post about how to start choosing a framework: SO 1, SO2, Here is a list of PHP Framework.
You can develop PHP on Windows, Linux or Mac.
Getting a web server setup
To run PHP and MySQL locally on your computer you will need to install Apache webserver with php module and MySQL database server. ie. a LAMP webserver (Linux Apache MySQL PHP).
In the past, I would recommend installing Ubuntu. These days, there are a few solutions available that will give you one click installation webserver without using linux.
For Windows:
http://www.wampserver.com
For OSX:
http://www.mamp.info
After having a LAMP webserver use w3schools.com tutorials to start.
I would say a basic one would be HTML. ;)
No Php framework expert.As templating which make the system much complex then as it.
Understand business logic requirement and think the cons/pro.Hoping for SA to think all for you is not good programmer.
No ajax.I dealing with large of data,rendering to one js file about 4000 k data is very bad.
Start from notepad or VI
After learn php about 1 to 2 years,try learn other language like c# or c++ to improve your php application.
Php is addicted language rather then other language.You type it works.Other language,you type It's Compile It's Hang up.
7.For complexity application,php is the best to me rather then other language,because you think,you write it works.
You should know how to use effectively at least one Debugger/IDE. It is amazing what you can learn from your code by stepping through it and watching it run. It both makes it much simpler to track down bugs, and improves the quality of your code. I believe you should never commit code to a project that you haven't seen execute.
The PHP Language
Go to PHP.net and read through all of the documentation. When you are done, you won't know everything you need to know about php, but you will know where to look.
Be careful of code snippets you find on the web. Often they contain sql in html, which is bad practice, as well as security vulnerabilities such as sql injection. I've seen few that use prepared statements, which is good for security.
Personally, I found the book "Build your own database driven website using PHP and MySQL" extremely helpful.
Other than that, the one thing I found hardest to get used to with PHP is how relaxed it is, compared with any other language I've ever used. By that I mean no types, flexibility about syntax and punctuation. Personally I think that's a good thing, but I also know that it probably encourages pretty bad behavior.
Here's one other tip I have: try to use something like the DRY principle -- i.e., you'll find yourself writing the same little (or big) bits of code over and over again -- make them into functions as early as you can in the process of coding, and life will be a lot easier later on.

PHP Object Oriented or not? [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 8 years ago.
Improve this question
I have a start of a webapp that I wrote without using the Object Oriented features of PHP.
I don't really know if it is worth it to go back and rewrite the parts I have finished. Is object oriented PHP worth rewriting all or part of a decent working app?
Given that you have an incomplete app I would say that reworking it into an Object based app will probably be helpful.
One thing to consider is the expected size of the end application. Below a certain complexity Object based may be overkill except for the learning experience.
I started out avoiding Objects like the plague because my initial introduction to them in university classes was terrible. I somewhat recently had to work on a project which was implemented in php objects. making the required changes was much easier than other projects. I have since then worked in the object model frequently and find it very handy for quick creation and easier upkeep.
Just to disagree with the consensus... I would say no in most cases. Not as an academic exercise on commercial code anyway. If it's working don't re-write it. If you have to go in to change / add bits, then refactor towards OO practices (there are lots of posts on SO about refactoring when you are changing code anyway, and not just for the sake of it).
In practise if you haven't done a lot of OOP, then you'll want to start small and get a feel for it.
Once you get a handle on the basics, a good beginners guide to Design Patterns (I like the Head First book) is very useful. Most PHP books would teach you OOP fairly poorly. They teach you about inheritance, but usually don't teach you about loose coupling and favouring composition over inheritance. A design patterns book will give you a better insight into this.
PHP still has a reputation for not "doing" OO right. I don't think this is fair, but is a reflection of the fact that it's so easy for people to get started without really grokking OOP. I would go out on a limb and say the majority (ever so slightly - call it 51%) of PHP programmers aren't comfortable with OOP. I think it's possible to do good OO in PHP, and if you're already comfortable with the language it's a great way to grow your skills.
EDIT:
Just to add a couple of disclaimers...
My comment about most PHP programmers not being comfortable with OOP wouldn't apply to the current SO audience!
Not suggesting you aren't comfortable with OOP, this applies if you're not
Typical answer: "It depends."
I tend to write the display page as a start-to-finish, < html > to < /html > scripted page. But the things that happen on that page were objects. Kinda like a poor man's ASP. While you can have OOP-base output, I alwasy thought it too cumbersome for a task as tedious as dumping data to a browser.
So, business rules and data access were OOP. Presentation was script.
If you have business rules that are not OOP, I would seriously consider writing those as objects on two conditions: (1) is "Do you have time/effort/money to do so?" and (2) is "Do you have a good PHP IDE that will make your life easier?" If it works, and changing it means writing in Notepad++, then I would call it done. :-)
I wouldn't say it is critical, but if you are going to go much further with the app, I would recommend doing it now while it is not as much of a monumental task. I would say the maintainability of a well written OOP program could far outweigh the up front costs. Especially when you consider that you will be able to refactor much of the code as you go along.
Learning object oriented techinques will be really useful, especially for programming in other languages in the future.
Since you have only just started the application, you could rewrite and improve the parts you have written. It depends on your deadline.
There are two possibilities: either your app is a one-off that just has to work right now and will never be touched, adapted, expanded or modified, or else your app is the beginning of something that you will keep working with and using over a long time.
If the former, don't break perfectly usable code. You have better things to do with your time.
If the latter, you have to bear in mind an important fact about PHP, which is this: poorly written PHP is a nightmare to maintain. Not as bad as poorly written Perl -- because what is? -- but bad enough that sooner or later you will feel a strong urge to steal a time machine, travel back to the moment you wrote the code you now find yourself maintaining, and stab yourself in the eye socket with an icepick.
So if you're going to be maintaining this code over time, take the time to do it right. That means: some kind of templating system, no PHP tags embedded inside HTML, separate files for separate functionality, and classes classes classes!
Your eye sockets will thank you.
I would say try and go OO just because what you have can be reused much easier than procedural if done right
I will also say that OO is much more organized then procedural. When your at a small scale it's easy to get away with sloppy code OO or not. But when you get to larger projects your procedural must be much more organized and thought out. Where as on some larger projects OO tends to force you to be more organized making things a little easier.
No, i think if the app is working like it should there's no need to rewrite it.
PHP isn't really OOP at all. They try hard but sometimes i think even the PHP-Developers dont really understand the sense of OOP.
If you wish to learn OOP (which is surely a good idea) try a real OOP-language like Smalltalk to learn the basic concepts. Java is also nice 2 learn the basic, although it isnt fully OOP as well
I'd like to reiterate the other answers here. It depends upon size of application and how much you'd like to learn about OOP. I'd be careful of learning OOP by using PHP though.
As for how much PHP is object oriented... PHP4 had some OOP elements slapped onto it, PHP5 is better but it's not baked into the language. PHP works both ways, and personally I like that you can choose.
In my mind, we phper can thorouly throw away the concept of Object(class instance), we only need Array and Mode Class:
All arrays in initial mode support any array function as it's method:
<?php
$array1->array_flip(this);
?>
Use ->mode() to validate the minimal data set, and then switch mode class:
<?php
$array1->mode('class1', $success);
?>
Any mode class has no ->construct() in it, but has ->validate() to validate the minimal data set.
The array in a mode still could use array function as its method, but after using any of them the array will be switched back into basic array mode,
and we need to use ->mode('class1', $success); to switch mode back.
The radical thought is data-centric programming, we need separate the data(array) and the activity(class method).
We could modify PHP engine, to get rid of parts of OO(object oriented), and support Mode Class, we could call it MyPHP.
For example:
$array_man1 could be set into two modes:cls_normal_man and cls_crazy_man:
<?php
$array_man1->mode('cls_normal_man')->normal_method1()->mode('cls_crazy_man')->crazy_method1();
?>

Categories