Php file structure best practices
When starting out with PHP, it can be daunting figuring out how best to organize a project. If you've ever been confused with where to put your images, external libraries, or keeping your logic separate from your layout, then check out these tips; they'll get you heading in the right direction. Show Tutorial Details
Directory StructureI'd say the number one thing in getting your project up and running quickly is having a solid directory structure you can reuse for multiple projects. If you are using a framework, usually it will provide a structure to use, but in this scenario we're working on a simple site or app. Breakdown
The Config FileAs designers and developers our main goal is to do as little work as possible. One way to reach this goal is with config files. To get a better idea of what the configuration file should have check out this example. array( "db1" => array( "dbname" => "database1", "username" => "dbUser", "password" => "pa$$", "host" => "localhost" ), "db2" => array( "dbname" => "database2", "username" => "dbUser", "password" => "pa$$", "host" => "localhost" ) ), "urls" => array( "baseUrl" => "http://example.com" ), "paths" => array( "resources" => "/path/to/resources", "images" => array( "content" => $_SERVER["DOCUMENT_ROOT"] . "/images/content", "layout" => $_SERVER["DOCUMENT_ROOT"] . "/images/layout" ) ) ); /* I will usually place the following in a bootstrap file or some type of environment setup file (code that is run at the start of every page request), but they work just as well in your config file if it's in php (some alternatives to php are xml or ini files). */ /* Creating constants for heavily used paths makes things a lot easier. ex. require_once(LIBRARY_PATH . "Paginator.php") */ defined("LIBRARY_PATH") or define("LIBRARY_PATH", realpath(dirname(__FILE__) . '/library')); defined("TEMPLATES_PATH") or define("TEMPLATES_PATH", realpath(dirname(__FILE__) . '/templates')); /* Error reporting. */ ini_set("error_reporting", "true"); error_reporting(E_ALL|E_STRCT); ?> This is a basic drop-in config file. A multi-dimensional array serves as a flexible structure for accessing various config items such as database credentials.
Using constants for commonly used paths makes include statements ( Using Different Config Files For Multiple EnvironmentsBy using different config files for multiple environments you can have relevant settings depending on the current environment. Meaning, if you use different database credentials or different paths for each environment, by setting up the respective config files you ensure that your code will work without hassle when updating your live site. This also allows you to have different error reporting settings based on the current environment. Never ever display errors on your live site! Displaying errors on the live site could expose sensitive data to users (such as passwords). The LayoutReusable templates are another big time saver. There are some great libraries for templating (such as Smarty), and I always encourage using such a library rather than reinventing the wheel. These libraries offer a lot of functionality (like helper methods for formatting currency and obfuscating email addresses). Since this is a simple site however we don't want to take the time to setup the library and will be using the most basic of basic templates. We achieve this by including common sections or modules in to our site pages; this way if we want to change something in the header, like adding a link to the global navigation, it is propagated throughout the site. header.php
rightPanel.php
footer.php
index.phpLet's say that we put all of our layout components (header, footer, rightPanel) in our resources directory under templates. Taking It FurtherWhile this basic template system gets you off to a great start, you can take it a lot further. For instance, you can create a class or functions that include all the template files and accept a content file as an argument to render within the layout. This way you don't need to keep including the template files in every page of your site, but rather abstract that logic out meaning even less work down the road. I'll show you a quick example. /resources/library/templateFunctions.php0) { foreach ($variables as $key => $value) { if (strlen($key) > 0) { ${$key} = $value; } } } require_once(TEMPLATES_PATH . "/header.php"); echo " index.phpThis is assuming you have a file called home.php in your templates directory that acts as a content template. $setInIndexDotPhp ); renderLayoutWithContentFile("home.php", $variables); ?> home.php
Benefits of This Method Include:
SymlinksOn Unix based systems (os x, linux) there is a neat little feature called symlinks (Symbolic Links). Symlinks are references to actual directories or files on the filesystem. This is really great for when you have a shared resource, such as a library used between multiple projects. Here are a few concrete things you can do with symlinks:
Using SymlinksSymlinks vs HardlinksSymlinks, or softlinks, act as references to full paths on the filesystem. You can use symlinks in multiple locations and the filesystem treats them as if they were the actual file or directory they reference. Hardlinks on the other hand are pointers to a file on the disk (think shortcuts in windows); they take you to the actual location of the file. There are a few things you should consider when using symlinks. Your server configuration must be set up to follow symlinks. For Apache this is done in the httpd.conf file. Find the Directory block and make sure that Options FollowSymLinks is there. If not add it and then restart Apache.
Creating Symlinks in OS XThere are 2 ways to create symlinks in OS X:
Creating Symlinks in WindowsTo accomplish this in windows you'll need to use the mklink command in the command prompt: C:\mklink /D C:\libraries\myCustomLibrary C:\Users\derek\Sites\mySite\resources\library\myCustomLibrary Summary These tips are meant
for beginners or those creating simple sites or applications. Ideally for larger applications or sites, you'll want to consider something more advanced like the MVC architecture and Object Oriented programming. I encourage you to look into these once you've gotten your feet wet and feel that you've outgrown most of the steps above. I decided not to cover source control as it's a pretty large subject on its own, but these tips should help you in organizing your files for easier source control if
desired (hint: store stuff like layout images in your resource directory and symlink it into your Hope you find these tips helpful when starting your next PHP Project. Thanks! Resources
Did you find this post useful?
Boston based web developer whom primarily lives in PHP, but breaks things in Objective-C from time to time. Loves working with front-end technologies such as HTML, CSS and Javascript. Feel free to follow me on twitter or check out my blog. What is the best practice PHP?PHP Best Practices To Follow in 2020. Always Use PSR- 12 recommendations For Error-Free Coding. ... . Make Your Code Concise and Readable With the Twig Template. ... . Composer Acts As a Dependency Manager. ... . Use 'Namespaces' To Avoid Name Collision. ... . Always Use the Autoloader Function in PHP.. What is PHP file structure?1.2. Structure of a PHP Script. PHP is an embedded scripting language when used in Web pages. This means that PHP code is embedded in HTML code. You use HTML tags to enclose the PHP language that you embed in your HTML file — the same way that you would use other HTML tags.
Why is PHP so fast?PHP is much faster than other options (such as ASP) because of its faster load time as a result of its own memory space that removes most of the overhead in execution.
What are the coding standards in PHP?PHP Coding Standards Edit. General. Opening and Closing PHP Tags. ... . Naming. Naming Conventions. ... . Whitespace. Space Usage. ... . Formatting. Brace Style. ... . Declare Statements, Namespace, and Import Statements. Namespace declarations. ... . Object-Oriented Programming. ... . Control Structures. ... . Operators.. |