Related
Ok, it might be a banal question but i'm a little bit confused.
I'm going to develop a project by my own. This means i'll build the HTML template, the PHP scripts, MYSQL query, AJAX calls and CSS styles.
This means no other people will touch any part of the code.
I know templates are good ways to make the entire application easy to be modified. But is that so necessary to do it? Since i'm the only one who got to know what that files and what that page do?
Using common patterns in the development of software products is not only about making it more readable/maintainable but also about making it extensible. The longer your software will be in use, the more features will be requested/desired. Extending one big mess of a software will not work out in this case.
Try a php framework (e.g. Zend Framework / Symfony(1/2)), there are lots of tutorials which allow you an easy start with or without templating engine (I use twig atm, which does a great job!).
If i were you, i wouldn't use templates (do you mean PHP frameworks?) but thats just me.
You don't have to use a template engine - PHP itself can do that just fine.
In general, it's a good idea to "separate concerns" (eg. code which outputs HTML is separate from code which loads data from the database) - it improves the readability and organization of code, making it easier to maintain and faster to develop further.
You should have a look at a framework, like symfony. Most frameworks make use of MVC and hence provide a good separation of your code.
But is that so necessary to do it? Since i'm the only one who got to know what that files and what that page do?
Yes, if you want to keep it maintainable in the long run. If you are not constantly working on the code, you will forget how some things work eventually and then you are happy if you have a proper separation and organization.
I'm a PHP developer. I like PHP! It is a really good language if you know how to use it, but I know it allows very bad design sometimes.
It reminds me of JavaScript which has good parts and bad parts. One particular project, CoffeeScript, tries to focus only on the good parts, forcing you to write good code.
I was thinking if something similar could be done with PHP... A new syntax that would be compiled only to good PHP code taking advatage of all the new and exciting stuff we can get with PHP 5.3.
So, getting ahead of some people, I'll ask: Why create a new language on top of PHP if you can just use Ruby or Python or something else?
PHP is easy to deploy anywhere
The language itself has a lot of good features and ideas
There are lots of good libraries written in PHP
...
So, my real questions here are...
Is this a stupid idea? Why would it be? Do you think CoffeeScript is stupid?
How do someone starts to create a new language on top of another? I know nothing about this, but I would like to learn. Where to start?
The idea is definitely not stupid, especially if executed well.
I like coffeescript a lot, but it has it's approach has downsides as well. Debugging a coffeescript script still requires you read the generated Javascript code, which can be tedious, since you haven't written it actually yourself.
I've understood that Jeremy Ashkenas, the creator of coffeescript has started to work on coffeescript after reading "Create your own freaking awesome programming language" by Marc-André Cournoyer.
Good luck!
The reason CoffeScript is a good idea is that if developers want to run code in a client browser they have to use javascript; so the only way to program in a different language is to allow that language to be convertible to javascript.
I'm not sure the same really applies to server side programming. If you've got issues with PHP and want to use a new language there is no real advantage to having that language generate PHP.
On the other hand, a language that was very similar to PHP, but fixed some of the flaws would be a great idea.
Heh, great idea. My thoughts, some contradictory...
There are precedents for civilizing bad languages by putting syntax preprocessors in front of them.
In the early days of Unix, Fortran was popular and about the only portable language because most machines had no C compiler. But the vanilla Fortran of the day didn't even have block structured if-then-else, just a goofy single-statement if or an if-goto. So, the Ratfor language was implemented as a preprocessor for Fortran-66.
I believe there were (are?) Cobol preprocessors that presumably dealt with the verbosity and limitations of early Cobol dialects.
To this day Unix-derived systems ship with a macro processor called m4.
Several CSS preprocessors are available today, most notably Sass and LESS.
But...
Just let it die, and the sooner the better
The problem isn't really in the syntax.
I don't see much of a JavaScript-PHP parallel. JavaScript is a great language. It's kind of the opposite of PHP.
I'm not sure why you say that PHP is a great language. It's one of the worst. Every decent feature is a patch or repatch in a recent version.
As you noted, there is a fixed-up version of PHP already: it's called Ruby and, as a language, it's near-perfect. There is another fixed-up version called Python. The world would be better off in the long run if we support the better systems.
It is here now. A new language which is to PHP what CoffeeScript is to Javascript. (I.e., awesome.)
SNOWSCRIPT
Snowscript code looks like this:
fn how_big_is_it(number)
if number < 100
<- "small"
else
<- "big"
PHP output looks like this:
function how_big_is_it($number) {
if ($number < 100) {
return "small";
} else {
return "big";
}
}
All it needs now, is you.
If it would be to PHP what something like sass is to CSS, I'd be interested. But what would exactly would you want to add? Or would you just want to weed out the bad?
And what would you consider to be the bad?
Writing a PHP syntax transformer would probably be a neat project.
However, don't forget that PHP's standard library is a huge mess. Cleaning that up, would be a far bigger task.
The more I am thinking about this, the more irrealistic it sounds. The reason is simple: There actually are such language proprocessors already. Two of them (though not using PHP as implementation, only as compilation target) can be found here. But simply nobody uses them.
Yes, if the compiler itself were written in PHP, probably more people would use it. But I really can't see a way how to get this popular enough to be worth the work.
Another big problem is, that people mostly are used to their awesome code-highlighting, code-completing, code-inspecting IDE. Without getting IDE support probably merely anybody will use it (and IDE support can only be obtained by having many people use it...)
Thoughts?
I can see writing compilers to JavaScript (because the web imposes it upon us), but this sounds like a waste of time.
Haxe already does this, although it's not specifically targeted at PHP (linked to the Wikipedia article instead of their website because I'm afraid I'm going to get exploited if I visit the real site...)
PHP is easy to deploy anywhere
...as are its vulnerabilities.
I know it allows very bad design sometimes.
That's a bit of an understatement, it doesn't even have a module system, has no encapsulation, and has tons of silly things such as dynamic name resolution.
PHP is slow enough as it is, do you really want something an order of a magnitude slower?
Java is much more easy to deploy anyways, and lets you drop down to the bytecode level if you want. Java also gives you access to moderately sane libraries.
This is something I have thought about already often. PHP just is messy at some points.
Actually, I already have a project PrePHP focusing on providing PHP 5.3 functionality to PHP 5.2. But it adds some minor language features, like func()[0]. I haven't developed this project for some time and it definitely isn't "clean", but it shows, that what you want is possible and actually even not that complicated.
If you are serious about this, I am perfectly willing to collaborate with you.
Very interesting idea and if it come to life i think that i wan't to be involved in :)
For start You may check and read this position http://www.amazon.com/Masterminds-Programming-Conversations-Creators-Languages/dp/0596515170 (iam reading it now). It makes clear how really complicated is to maintain own language.
I agree that PHP definitely could do with some improvement, right now it allows for too much fooling around.
Some things I'd like to see
Static Typing
Required indentation
Proper use of objects (using arrays as objects is just stupid)
Then again, maybe I should just drop PHP and start working with Ruby or Python.
I'm like 8 years too late, but I'll answer anyways for anyone else who stumbles upon this.
Hack is a language developed by Facebook to deal with some of the issues of PHP, since Facebook had a large PHP codebase. Hack adds some nice features on top of PHP such as gradual typing (what TypeScript has) and generics, among other features, and gets rid of some of the more dangerous PHP features. Hack was at one point a superset of PHP, but is no longer completely compatible after removing some of the worse PHP features.
This is slightly different from what you were asking, since at this point Hack has its own interpreter, written by Facebook, but this started out as "better language that compiles to PHP", so I thought it was worth mentioning here.
I have been learning php, by just plugging away at it.
I was hoping someone could point me in the right direction in regards to security, flow and general best practices?
Thanks.
edit--
I suppose a better way to phrase what i am trying to ask is..
What is the best practice:
1.) when processing forms with php, get vs post, $_REQUEST vs $_GET & $_POST
2.) when dynamically creating HTML files (example below)
3.) logins & authentication in the same file as the form creator
4.) Sending e-mail with php
From #2 above
<?php
echo "<h1> Welcome </h1>";
if ($_SESSION['type'] == "admin")
{
//lots of html in the echo statment
echo "tables and admin interface here";
} else
{
//lots of html in the echo statment
echo "tables and user dashboard here";
}
?>
--VS--
<h1> Welcome </h1>
<?php
if ($_SESSION['type'] == "admin")
{
?>
lots of html in the echo statment
tables and admin interface here
<?php
} else
{
?>
lots of html in the echo statment
ables and user dashboard here
<?php
}
?>
--VS--
<?php if($_SESSION['username']): ?>
<p>You are logged in as <?=$_SESSION['username']?></p>
<p>Logout</p>
<?php endif; ?>
ps:
Thanks to everyone who already responded.
Can I also inquire where does a framework fit? I took a class in OOP and we didn't become familiar with any frameworks.
I read lot on the Symfony and zend frameworks but am still confused.
thanks again.
Good programming is irrelevant of language. I suggest you start studying software development concepts such as object oriented programming, design patterns, separation of concerns, reuse, encapsulation, testing and refactoring. Start at any of those and keep "plugging" away at the list and you will get better.
PHP specific - learn the accepted coding standard, such as PEAR's or Zend's. After you've assimilated some of the concepts, pick up a good reference such as one of the top frameworks mentioned in the other answers - Zend Framework, CakePHP, Symfony among others.
The PHP community has never really been strong at offering up any development guidelines or advocating best practices. In the pre-framework days typical php code written by most devs was very amateurish and disorganized - see the Wordpress source code. But PHP is a good language for web apps. It was made for the web and you can write good professional code with it if you want to. It's trendy to bash it but disregard that stuff.
Anyway, like the others have said here your best bet is to use a framework. Being a newbie, it will be important for you to pick a framework that is well documented and has a strong community to help you get over the hump. Here's my rundown of the major php frameworks:
Kohana => a good one but poorly documented with a weak community. skip it.
Zend => the most popular framework for php w/good docs but another poor performer as it's overdone with objects and patterns in an attempt to be overly enterprisey.
Cake & Symfony => are 1st generation php frameworks and also have a rep for poor performance. I'd skip both. A new version of symfony is in the works but not ready.
Lithium => cutting edge new framework led by one of the Cake devs. using php 5.3 and claims to be fast. BUT, not at v.1 yet & also have poor docs at this point => http://li3.me.
Codeigniter => popular, fast, good docs and community. very easy to learn. v2.0 hasn't officially been released but is ready for production use and is php5 only. You can use the same documentation that is on the CI site for v1.7. The versions are very similar except 2.0 drops php 4 support finally. here is the download for 2.0: http://bitbucket.org/ellislab/codeigniter/
YII => Really gaining momentum despite it's goofy name. It's a fast performer with GREAT documentation and a ton of features. A new book is out too. The community is so-so but growing. This framework imo takes a lot from rails. There a web-based code
generation tool and it uses active record. http://yiiframework.com/
you can build apps a lot quicker with YII due to the code-gen and active record but it will be a bit harder to learn than CI. You may find it getting in your way a bit more too as you try to do everything the YII way. CI is more flexible - gives you the foundation you need w/o getting in your way. So for now i'd recommend codeigniter.
good luck!
Use a freely available framework such as:
Zend Framework
CakePHP
CodeIgniter (See comments)
Kohana (From #Alex's answer)
and follow the standards specified by that framework.
Take a look at a reputable open source software, that is known for good code.
Look at Kohana's source, or any of the others from Billy ONeal's answer.
I wouldn't recommend using CI's source as a guide - as I think it still supports PHP4, so some of the code will be useless to learn - unless you plan on writing PHP4 code, which is a bad idea if you are only learning now.
Do not look at WordPress, you will pick up some terrible habits.
Also, while I think of it, learn about OO, and the difference with procedural code.
Why does everyone attack php? Many many excellent sites run off it. At least until they get big enough to merit an overhaul.
99% of the internet is just throw away sites that don't get much traffic, compared to sites like facebook or amazon, so why should they care to learn a language more sophisticated, stable, or strict, if php gets the job done in a cost effective way that is no less stable or secure for what is needed?
Most of the sites I build run off Kohana - a branch from codeigniter. Both are useful. Who cares if CI uses php4. What if you get hired by a web firm that has archaic sites? Guess what - you will need to know php4. That complaint is like saying you no longer need to know tabled html... until you have to design and code a newsletter template for some big company. Then what? Crash course it with google searches?
I say the RIGHT way to use PHP is to follow examples. Yeah wordpress has some awful habits, but it works and is only one of the most successful platforms out there. What does that tell you?
I would say you could learn a lot from a framework like Kohana - and even CI - since both have decent security methods that are not hard to follow. Things like database escaping and xss filtering. It will ween you into OO programming if you are not familiar and both have a decent userbase so you will not get stuck with no answers.
Don't let these guys scare you. for beginners PHP is a good move. Eventually something like Java or objective C will be more beneficial for jobs and application, but learn it when you get there.
It is possible to code well in PHP. Probably the best resource I've seen so far as to just how is here in StackOverflow: browse the questions marked PHP.
In no particular order, some specific things to help you on your way from my years programming in PHP:
Enable Notices and then make sure you don't write code that triggers them. PHP's default install doesn't enable Notices, which is fine for a Production environment, but bad for a Development environment. Unfortunately, their default php.ini file doesn't seem to know which it is being an example for.
Similarly, make sure you have magic_quotes and register_globals both turned off. They are both designed for more simple and naive programming times and today create more problems than they solve.
Initialize variables before you use them. This also means array elements. If your code isn't sure if the variable or element exists, use isset() and array_key_exists().
Pick or develop a sensible coding style and stick with it. You don't need to be frugal with whitespace or linebreaks.
Check for variables you are expecing to be there. This is a tricky one. A great example of this is when processing a HTTP POST that may have a lot of variable elements. Figure out what should be in $_POST and look for that. Don't assume that what is submitted is always going to be what is supposed to be submitted.
Along the same lines, check for the correct values, not the incorrect values. If you need a variable to have a valid value, look for what constitutes a valid value before proceeding, not what might be an invalid value to throw away. For example, if you need a submitted variable to be an integer, then check it's an integer, don't check for a null-string as a null-string isn't the only invalid value!
Separate database access, logic and presentation (this is often called Model-View-Controller programming). Another way of putting that is that you shouldn't be comixing code that is processing ther last POST request with HTML markup being emitted with SQL queries. Most frameworks will enforce this.
If you're not using a framework that provides an Object layer, you will be rolling your own SQL. Either use prepared statements, or use the DB's own quoting function for strings, not addslashes().
It was very easy in PHP 4 to use a lot of memory because structures got copied, not referenced. PHP 5 largely solves this specific problem, but it can still happen with strings. This also doesn't address the tendancy of some APIs to create large structures.
To provide something other than "use a framework" or "look at a framework," here are quick rule-of-thumb PHP-specific practices I've found that make a big difference.
Use PDO and abstract it into a class (or use an existing class). Do not use mysql_query or such functions.
Logic before output. Do not do things such as <?php if($x) { ?> HTML here <?php } ?> (using HEREDOC syntax helps enormously with this).
Use the __autoload magic method to limit includes
These alone would be night-and-day transformation of a lot of ugly PHP code I see. Then there are the obvious language agnostic rules such as consistent naming conventions, self-documenting code, etc.
I have been looking around online and I cant seem to find an article on this that isn't totally outdated. Does anyone have any good articles that give some good advice? What I have read so far is good, and a bit helpful, but I want to have modern code examples, not ones from 2002.
I have coded an extensive PHP/MySQL program and I am trying to make it better now, any suggestions?
EDIT:
People are suggesting frameworks, and I appreciate it but I am looking for coding tips for raw PHP Coding. The whole application is already done and it would be very lengthy to recode the entire thing in a framework.
I will be checking those out for future projects though. Does anyone know or have any tips for Writing Clean and Efficient PHP Code?
Use Smarty
Write to patterns as much as possible.
Edit for the Question Edit
Clean and efficient PHP isn't much different than any other language. Practice good Object oriented principles. Focus on Encapsulation, Separation, and Polymorphism. Refactor often, and Utilize design patterns as much as possible.
There are many sites that focus on these principles. Some use Java, C++, etc. to demonstrate the principles, but it shouldn't be too difficult to convert them over to php.
I'd take a look at the Zend Framework. It is a great framework that encourages PHP developers to use better practices like MVC, OOP etc. If you are not used to this paradigm, I have to say that it will seem daunting at first, but if want to continue with your PHP development I'd suggest downloading it, and start the "Getting Started" tutorial.
There are other frameworks, CMS tools that you can download, but the Zend framework offers are very raw approach to building great PHP applications.
Acorn
PHP Classes helped me a lot (when I was coding PHP). Reading better code usually helps improve my own.
If you haven't already, I suggest making your PHP code object-oriented. It promotes reuse and makes code a lot more readable. Here's a link to show how useful it can be for reducing lines of code etc.
Use CakePHP. It's an excellent MVC framework. Steep learning curve, especially if you've not used MVC before, but the tradeoff is certainly worth it.
Like folks said, frameworks are the way to organize your code best. Many support Model/View/Controller; many are object-oriented already. Try to stick with a PHP5-specific framework (the code will be much cleaner; PHP4 did not support OOP fully). Try to go with the simplest possible templating engine. One PHP5 framework I like that hasn't been recommended yet is called QCubed.
One thing in your post worried me, though - you're saying that you already have the application written, and are now trying to make it "better". If that's the case, trying to switch over to a framework now may be a HUGE (literally huge) task. If this is an application you expect to be in production for 3-5 years, I'd consider taking a plunge; I'd then try to take little pieces of the application and integrate them into that framework environment. Doing it wholesale is a recipe for pain.
For clean PHP code you can use PHP CodeSniffer (search for CodeSniffer on http://pear.php.net since direct links don't work) it's an automatic code style checker. You can define your own codestyle rules and then check the code.
You can even script it, so your code gets checked before SVN commit.
This isn't a question about what framework to use. I've learned both Rails and Django, and I write all of my webapps in PHP. My question is why bother with the frameworks? It's always taken me longer to use a framework than to reuse old MySQL code and build "models" with phpMyAdmin. I also like writing everything myself, because I know what's going on. I can still reuse functions, etc. and do things how I want, and this freedom seems to be missing from most frameworks.
I'm not saying that my way is right; in fact, I'm trying to figure out where my logic fails. The hype can't be just thin air. What am I missing?
The basic idea of a framework is to allow you to work at a higher level of abstruction and write only the code you have to write to implement your specific requirements. All the other repetitive stuff is handled for you by the framework, and probably with far fewer bugs and security holes than if you did it yourself.
It may feel like it takes longer to learn a framework than to just do it yourself using basic language features and standard APIs, but it's simply not true - not if the framework is good and the app is non-trivial, and especially not once you have learned the framework (using a different one for each new project would of course be idiotic) and factor in the time it would take to find and eliminate all the bugs and correct all the design mistakes that have long since been found, eliminated and corrected in the framework by its developer community.
Almost every developer has cowboy coder instincts that tell him "Doing things yourself is much more fun than using code others have written, and I'm sure I'm good enough to get it right the first time, so it will even be faster and better!". These instincts are almost always wrong.
Frameworks allow you to concentrate on the application itself rather than worrying about the boilerplate code that you'd otherwise have to write for every application. They allow you to structure you site in a much more logical (mostly object-oriented) way, using tried and tested design patters such as model-view-controller. The code in framework is generally more mature and of a higher standard than code you would write yourself for one-off projects as framework have a large community of developers perfecting the code perfecting the code over year. This means that framework-driven sites often perform better and are much more secure.
You also mentioned you like writing things yourself - I know where you're coming from. My solution to this was to write my own framework - I get to reuse and improve my code with every project I do and I know the entire codebase inside out.
Writing it your self may make it easier for you to understand things your self but unfortunately it can make it much harder for other developers to understand what is happening. Frameworks will often be better documented and have a larger community that can support a new developer that is working on the app that you wrote.
I think a big part of it is what you focus on. Frameworks standardize the parts that you shouldn't have to keep revisiting, which helps you focus on the application as a whole. If you reuse your own code all the time you're already using your own makeshift framework.
Your comparing a framework (Rails) to a language (PHP). A framework is going to give you pre-built components so you can spend time on what makes your project unique.
You may already have a code base that helps do this for you. Check out some of the PHP frameworks since that's where you are more comfortable. Take a look at CakePHP, CodeIgnitor and/or Zend Framework.
If you are building many small apps/sites, using a framework may make your life easier.
I think a good step for you is to create your own framework with the code you've programmed so far. ;)
Try to make your code parametrizeable, in other words: create components which you can reuse in different parts of a website (for instance: styled containers), or in different websites (form generators/validators).
You can even go further and create base-classes from which you extend new classes to build your websites. (for instance: data objects with generic select/insert/update/delete methods).
I bet this gives you the best view on why frameworks are so damn handy ;)
It'll take you longer to initially use a framework for the same reasons a PHP developer would take longer to initially use Ruby - you're not familiar with it.
Once you're familiar with them, frameworks can offer the ability to skip the mundane and focus on actually writing the important parts of the app.
You should also just use a PHP based framework like Symfony or CakePHP using them should reduce your production time considerably.
One reason to use a frame work is code separation. Take symfony for example. The model is all done with propel or doctrine libraries. Very little SQL needed. You instantiate a new object and user getters and setters, to store your data, and instead of writing SQL in your page code you create functions in the objects related to the query. When you need to access the same kind of data on different pages you are asking the model for it, keeping the business logic with the model where it should be, so there's never any difference. All the work is done in the "action controller function". You get all the data you need, and then put as little php in the display, basically just echoing the variables you got in the action controller, (with the exception of some for loops and if statements for conditionals. I have found this a more efficient way to code, and on my 2nd project saw the production time cut in half.
You don't need to learn a new language python/ruby just to use a great framework, just have to fin one that works for you.
First, PHP has frameworks too, so the question as stated misses the point.
Yes, you can write your own framework, and as Kris said, there's no shame in that. However, part of the leverage of code reuse is the collective value of the efforts of many. It's not just about reusing your own code. Frameworks encapsulate the common tasks and patterns we all share and provide well tested solutions with many iterations of improvements from the community. No individual effort is going to measure up to that, no matter who you are.
If you roll your own, it will only become world class due to the collective effort of world class people, and that will only happen if your idea merits the attention. The top frameworks out there are already proven on those criteria.
DHH is a smart guy, but the Rails we have today never could have been realized by him alone. Not even close.
If you like "writing everything yourself" as you say, then choose a framework with a core philosophy that matches yours, and start making core contributions in the areas where you can see room for improvement.
Depending on the functions of your Web Application, it can be faster to develop without a framework. For example when the Webapp is just some kind of data viewer.
But as soon as you begin to implement more advanced functions, you are much more efficient with a framework.
Try do do this from scratch:
- proper Form validation
- Handling of multiple Language and Date/Time formatting
- Authentication
See a framework as free tools and stable implemented function for you to use.
Sounds to me like you have already written your own framework in php, since you do mention code reuse.
I can imagine it being easier to use your own set of wheels instead of adapting to someone else's. No shame in that.
Frameworks are there mainly to help people who are semi-new to PHP (or the specific language it is built on) to be able to build a website to an extent that it is secure and easy enough to add on extra parts to the site without having to know a lot about the specifics like security, MySQL (or other database types). In my opinion it is a fairly good way to help break coders into a language, allowing for the fact that the framework isn't too complex of course.
EDIT The reason behind me saying they are for beginners is because myself, as a beginner has used frameworks to break myself into languages a lot better.