PHP code design, structure, pattern ..? [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 4 years ago.
Improve this question
I want to get some input from experienced PHP developers on how to structure code.
I feel my applications soon get "dirty" and unorganized.
Should I start coding in OO? Should I start using MVC? What about design patterns? What other options are there? How can I organize and structure my application code better (beyond proper indentation and naming)?
Links to resources are welcomed :)
If I decide to start coding using MVC? Should I use any frameworks or just hand code everything?
What is your suggestion.

Instead of worrying about creating something from scratch, I would start by using a framework and extend it with your own widgets. Zend Framework is excellent and has a massive community of support: http://framework.zend.com/
Otherwise, the best book so far I've found about PHP design is called 'Advanced PHP Programming' by George Schlossnagle. It explains patterns and design efficiently better than anywhere else I've seen.
As per comments below, I definitely don't mean to say that you should only learn a framework. It's never good to learn only a framework, but you can learn coding techniques through other peoples' code, like in frameworks/libraries/etc. Attack your learning through every source available (forums, books, code resources) and make an educated decision as to the approach you should be using when taking on a new project.

My suggestion : use the Symfony framework at least once, the tutorial will teach you most of the best practices you need to know, and let you organize your code in a good way.

Well for me JAVA is one of the best ways to really see how OOP is done. The way it's done in php is kind of lame. I've seen a couple of well structured maven based projects and I say "WOW" every time I see them again. You should start using the MVC model of coding as it'll make things easy for you to monitor - Controller = pages's logic, Model = page's (sql) data, Viewer = page's template.
Best you could see what I'm talking about at this site http://php-html.net/tutorials/model-view-controller-in-php/ .

Take it one step at a time. Download Smarty and get familiar with it. This should give you wonderful warm fuzzy feelings about separation of concerns, and give you some insights into other things to look into.

There is no silver bullet.
It doesn't matter how you start to plan, what matters is that you plan. Start with something basic like MVC and try to find reasons why your app shouldn't be made that way. If you can't find reasons, think about what frameworks might have features you are going to need.
If MVC is going to just add a lot of extra work. Such as if you are going to be doing a lot of complex AJAX or serious multi-level caching, or other reasons. Figure out what kind of system might save you time.
With heavy caching, sometimes basing the whole structure around a cache system can work. Tap into cached strings as templates and you can now alter pre-cached items. Useful for pages that are assembled on the fly iGoogle style.
The solution will come from the problem.

I would suggest you try to work with some popular framework. This way you can read clean code and form your style. 'Yii framework' is good enogh as for me. Offcourse, it will be useful to read about design patterns not only for your php skill, but for programming skill in general.

Related

My Content Management System [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 6 years ago.
Improve this question
I intend to develop a Content Management System (CMS) like shown in the figure below;
Figure: Intended CMS design
Is it possible to completely develop it using PHP's standard library?
Do I need to use a PHP web framework? If so, why and what framework is ideal?
I hope to use MySQL as backend.
I hope to use below technologies as front end;
HTML5 and CSS3 - hard code by myself (Is there any framework or something make it easy? I heard something lesscss.org)
jQuery - to make HTML elements functional
Ajax - to avoid page refreshing
Bootstrap - to make my CMS responsive
Are there any technologies I do use, or any suggestions?
I prefer to improve my HTML, CSS, PHP and other technologies by learning and hard coding. So I hope not to use CMS like
joomla, WordPress, etc. Am I right?
Please note: I've already searched Google extensively before I put my questions here. But I am unable to confirm what I do next. Your comments are appreciated.
Your questions really look well researched and I think everybody with the intention of building a custom-made CMS has come to this point where they ask themselves these fundamental questions (in other words: good questions!). Now to some answers:
1) Yes it is possible.
2) Although building a CMS in pure, native, hard-coded PHP is possible, I wouldn't recommend it for production. You could do it, and you would largely profit from the experience, but there are many little problems (like Routing / User-Management / Authentication / Communicating with Database / Form-Building (like in your screenshot) / etc.) that are already solved by a good Framework.
Also as you are a beginner, you are naturally overwhelmed by the problems and decisions you have to solve/make. This is also a good point why a framework would be a good starter. Although some solutions are sometimes a little too opinionated, they still give you a good structure to start with and most of the times follow best practices of our industry.
Which framework is the most ideal for your project, you'll have to decide on your own, based on your requirements, but some common ones are:
Symfony (probably the most known and most used php-framework, but also very abstract / I would recommend this on a really big project, where you work in a team and you are aiming for flexible maintainability)
Laravel (excerpt from their website: An amazing ORM, painless routing, powerful queue library, and simple authentication give you the tools you need for modern, maintainable PHP.)
Silex (the little brother of Symfony, info from their website: Silex is a PHP microframework for PHP. It is built on the shoulders of Symfony2 and Pimple and also inspired by sinatra.)
FatFreeFramework (from their website: A powerful yet easy-to-use PHP micro-framework designed to help you build dynamic and robust web applications - fast!)
As I used Silex myself many times and also when I began with best-practice PHP, I recommend to start with it, if you decide to write your own CMS. I pretty fast did some Management-CMS similar to your screenshot with it (with their Form-Builder) and was happy with the result.
3) Again this is up to you. For the backend you will probably use MySQL anyway, if you just need a database. In the frontend using HTML5/CSS you could try jQuery and Bootstrap (and then here their less or sass implementation).
If you really don't have too much logic for your JavaScript, you could also try to just use native JS, without jQuery. This way you will also learn more about the language and have less vendor-dependencies the user has to download.
4) If you are really up to learning a lot, then yes, you should probably hand-code everything yourself. This way you also have total control of what code gets delivered to your user. That's a problem with most common CMS: they pollute your code through some other plugins or something and you quickly loose control over your output.
But if you need to be fast there are also CMS that address this issue by giving you total control over your output and giving you creative freedom, like MODX does.
In the end it is up to you and especially the needs of your project. If it's a simple website and you conveniently want to edit the content and also have some starter-help, then I recommend to use a CMS.
If you really want to learn about all this stuff and you have some special needs, then go on and code your custom-coded application. In any way: good luck! :)

When can I start using a Framework (Laravel)? [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 9 years ago.
Improve this question
I want to start by saying that I searched a lot for this exact question, but none of them satisfied my needs.
I program Php, MySQL, HTML, CSS and Javascript the 'old way', using just a text editor and building every website from scratch. I built websites from the most simple to an-almost e-commerce just by coding every piece of the application. The most advance thing I did was using some simple classes, like a database wrapper, singleton, and for the rest I always used functions.
Now, recently I signed up for a website where there are courses ( I won't say its name because I don't know if I'm allowed ) and I followed one about Laravel 3 ( I know currently its version is 4.x ), and I must admit I fell in love with it. I like it very much and I want to start using it but I'm afraid that doing so will 'dumb' me.
What I mean is that Laravel has a lot of helper functions, Eloquent structure and so on, so by using it I won't learn any more the pure Php because for everything you need there is already a built helper function.
To make a very simple example, if you want to join some tables you use Eloquent and within literally 3 second you accomplish this. If you want to log a user in, again you have an Auth class that does everything for you, even setting sessions.
This is my biggest fear, that I won't learn anything anymore because all you need is already provided, you don't have to think that much anymore.
On the other side, Laravel helps you a lot and it eases your work very much. As much as I want to start digging into it more I can't help but fear its downsides.
So, do you think I should wait and learn more traditional Php before dive into a Framework?
When is the right time to start using one?
Look at all the sites you built. Identify redundant elements. Extract them into classes and functions and build your own framework. This will allow you to build sites faster and build a library. Once you do that, there's no dumbing down. You can choose to use another or not... but you'll have yours too.
That's what I did. I have my own framework. And it ain't bad!
There are two types of developers:
users - they can use stuff and get by
actual developers - they can build stuff from scratch and give users tools
Choose which model fits your needs best.
1st category goes for quick results, are efficient and get the job done. These guys should use 3rd party frameworks and libraries.
2nd category are artists pushing themselves further with each new piece of code they build. They go for performance over turnaround time, code beauty and functionality vs. just functionality, etc... These guys feel offended by 3rd party frameworks and libraries and always roll their own. Because they can!
There's another catch. Some frameworks might have too much fat for your needs. Building more specialized solutions might actually yield way better performance than a one-size-fits-all framework. That's another perspective.
Bafta mai departe :)

Is AJAX enough? Should I learn a PHP framework? [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 11 years ago.
Improve this question
I started learning programming 4 months ago. So far I already know some javascript(and jquery), php, ajax html and CSS. Yesterday I saw for the first time in one of the stack forums a question about PHP frameworks (zend, codeigniter...etc).
I hope these questions are not very stupid, because I am a beginner so I don't know much about this world yet, but my questions are:
1- Do I need to learn how to use a php framework if I just one to build ONE website?
2- Do websites nowadays rely more on AJAX + some php OR just PHP + some javascript?
3- How long does it take to learn and master a php framework like zend?
1) You don't need to learn a PHP framework, and in fact if it's the first website you've ever built I'd suggest building it without a framework just to get a feel for how PHP works when building a site. This way you understand things like database connections, session management, etc. that is often done behind the scenes with frameworks. Then later on try building it with a framework to get an idea for the design patterns and other features that a framework has built-in to avoid code repetition, security holes, etc.
2) I don't know what the difference between AJAX + some PHP and just PHP + some javascript. AJAX is a part of Javascript, it isn't a separate technology on its own.
Some websites use a lot of AJAX, some don't. It really depends on what you want the website to do and your particular design: AJAX can provide a smoother feel to the site, but can have complications when it comes to things like back buttons and bookmarks.
3) Depends on what you're doing with the framework: if you're only using 10% of the features you certainly won't become a master in any amount of time. It also depends on the complexity of the framework: I haven't used Zend but I know that the more complex the framework, the longer it will take you to learn it.
Learn as many thing as you can. PHP is a good start, becouse it's very popular and easy to learn and use. There are many great frameworks written in PHP (Symfony, Zend, Kohana, etc.). However, it's not a nice, well designed language at all. Keep it in mind, don't stop at php, learn it then make progress.
b) You will be able to build a large variety of sites with PHP+JS+HTML
ps.: AJAX is a technology, and as a knowledge, it doesn't worth so much as is.
Ajax is just a technology to call server side scripts from Javascript. The server side script being PHP. So, if you intend to use Ajax, you need to know PHP.
As for PHP frameworks, its good to build a few website from scratch using PHP to get a better understanding, but eventually, its better to adopt frameworks. Frameworks implement a lot of the functions and methods you need. No point re-inventing the wheel.
The answers to your questions are very subjective, but what I suggest is:
No you should not learn a framework to build one website. Just go and build it in any way you can. Frameworks usually carry a lot of additional concepts and methodologies. You will have to invest quite some time to understand how they work, but it will be really hard to understand why they work that way. Doing a website is a great experience, so just go and build something.
Lets say websites mostly rely on HTML / PHP / JavaScript. Ajax is just an additional capability, which you are already focusing too much. It's great that you know what Ajax does, but you should concentrate more on the essential things, like number one.
Lets say it takes two years of constant interest in the field. So at first you learn the syntax of PHP, then you start to know how HTTP works, then you experiment with HTML and JavaScript/jQuery/Ajax a bit more, then you try a Framework. You keep trying until you become a master. Zend Framework is one of the most comprehensive, so it will take a while to study how it works and all the related technologies it brings with it.
My final advice is to stay focused, build something, see what challenges it brings, solve those challenges and eventually become a master. Good Luck!
Question One - The short answer is: it depends on the type of site you're building. The frameworks you're talking about were built to streamline web application development, which make extensive use of databases and object-oriented principles. If you're planning on building a site with mostly static content, I wouldn't bother learning a framework just yet.
Question Two - Again, it depends on the site. The concept of AJAX has many applications, but most sites employ it to make a site more interactive (e.g. not refreshing the page to load new content). For sites with primarily static content, AJAX has fewer uses.
Question Three - It can take a while to 'master' a framework. I'm not that familiar with the ones you mentioned, but learning a framework is less about understanding it's syntax/quirks and more about learning how to approach a problem their way. Again, it depends on what you're doing.

Are there any PHP *websites* that have made their source available? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 8 years ago.
Improve this question
It's not hard to find example PHP code. The problem seems to be that most of it is frameworks/libraries/etc. This is great, but I'd like to see an example of an actual website.
This stems from my perception that I can't build anything but "toys." My websites tend to be fairly CRUDdy, and it feels like my sites are a bit of generic MVC stuff and a lot of "SELECT" and "INSERT" statements.
I just want some assurance that I'm not "doing it wrong" since these are personal projects, and I'd like to use them to get a job.
Below is a good site that also make its source available (which is very well commented and easy to follow/understand, from a Zend Framework standpoint)
http://www.dasprids.de/
Instructions/info for the source
http://www.dasprids.de/behind-the-site
Actual source
http://site.svn.dasprids.de/
Check out MediaWiki. That's the same software that runs Wikipedia, and it's open source.
It's worth noting that the php.net website is itself open source.
What about PHPBB, which is neither a framework, nor a library?
There are also plenty of Open Source websites you can find just by making some search. Especially blogs, content management systems, etc.
Edit: responding to the first comment to my answer, I want just to add that looking at Open Source websites would probably help to have an image of what large (or not so large) projects are, and also how things are done by experienced developers (for example using PDO, SQL transactions, templates, etc.).
But please take in account that most of the time, those projects are developed by several people. And since PHP does not have any coding standard and does everything possible to force the people to not use good practices, large, collaborative projects are not so good at improving your coding standard nor learning good practices. For this, books may me much more helpful, especially books about good practices.
It may be worth looking at wordpress. I haven't looked at the php behind it, but I know I learned a lot looking at the DB definitions.
Usually a framework is a good compromise between writing quality code and performance. Larger websites that need scale come up with their own custom hacks which eventually evolve into frameworks. In my experience writing in pure PHP it's too easy to go the quickest way to implementing a feature and end up with a mishmash of code, but others might be more disciplined.
It's not hard to find example PHP
code.
Good point is that you know how to find code. You said your code ends up in a generic MVC and CRUDdy, i think this is what most of the web applications around are doing. But the important thing to consider here is they do these MVC/CRUD stuffs in managed way and following standard Object Oriented Design Patterns.
If you want to get examples of real PHP applications then search for open source codes for that specific type application and not frameworks/libraries. Frameworks/libraries are a bunch of PHP CLASSES combined together following the application design architectures and they are supposed to provide you a code base to start your new project with existing set of usable codes, not that they give you the "application feel" rather "structured feel" at the starting point. But once you get along these frameworks/libraries working together to provide you a structured way to build your application, things will really ease later. Your job is guaranteed ;)
If you want to develop codes with these MVC frameworks then start with Codeigniter. It is well documented and as you stated your existing code turns out to be like MVC, you'll grab this framework and how to build with it in one shot. I've written a Hello World in Codeigniter you can refer to start with it. (Also Refer: Codeigniter Documentation)
To find code for real application (not frameworks/libraries) you might think of slightly changing your search queries, search for categories of web application or alike you want to see, not just for the code to do this and code to do that, always search for the better and efficient ways to code and develop things. Github, Sourceforge.net, Google Code are really great places to search for "real" & "cool" open source PHP applications.
Well, actually you can learn a lot by studying a solid framework like ie. the Zend Framework. If you would like to learn that I suggest you first have a look at the Zend Framework Quickstart and then start reading Surviving the deep end. Once you covered these, you should have learned the basics of the Zend Framework, and then you can start looking at open source projects that use it. As far as CMSes go, there are a few using the Zend Framework, like TomatoCMS and pimCore.
BTW Creating a website isn't exactly rocket science, most sites are in fact just a collection of dull CRUD screens (sometimes spiced up with some AJAX to deliver a better user experience) that are used to add content to the site...
On beta.mkforlag.com, where I try out new ideas and develop new pages and new layout for the main domain, most of the source code can be seen. Most of the site is in Swedish, but most of the php code (comments, variable names etc.) is in English.
You should also keep in mind that although I've been using PHP a couple of years I'm no PHP expert and most likely "doing it wrong" in many cases. If you're not that advanced, though, you may find at least some of my code useful.
My code of satya-weblog.com is almost live. I am using wordpress V 2.9, so download that and you know about my site!
Check at symfony framework also and you come to know of propel, yml etc

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.

Categories