PHP - Coding Practices For Large Scale Projects?
Hello all. I'm looking to build a website in php that will be large in scope and I'm looking for some direction as to how to go about coding it. What I'm referring to exactly is the programming model. I'm new to the language, but not to programming, and I've read up on it and familiarized myself with the syntax over the past few days. Normally when I go about building a project I like to plan ahead how I'm going to build It so I don't run into tedious issues later on and this is what I need help with.
My concerns:
I am looking to use the alternative syntax for control structures as to make the php code inside my html readable and easier to manage but in terms of OOP when is it best for me to use classes vs functions?
I am leaning towards using both classes and functions. Classes to handle polling data, sanitizing it and storing it while the functions will be used , with the alternative syntax, to display the data.
How should I go about properly setting my project assuming I will have many concurrent users using the website at once?
Is using xml / INI files as a directory to look up information a good practice? Is it better to declare constant variables instead?
When working with multiple includes is there an easier way to include a file than having to explicity write "dirname( dirname(__FILE__) )" everytime?
I'm essentially looking for guidance / tips as to good programming practices with this language Advanced practices are welcomed as well.
Development Tools:
XAMPP ( Windows 7 Pro )
PHPStorm
Current directory structure plan:
Here is what I currently have:
The API class is a collection of functions that returns an object to be used at a later data.
<?php /* * Development API Key * @since 1.0 * * Rate Limit(s): * 10 request(s) every 10 second(s) * 500 request(s) every 10 minute(s) */ define( "__API_KEY__" , "---------------------------------" ); require_once dirname( dirname(__FILE__) ) . "\\settings.php"; class API { // If successfull it returns an object from the url that's passed to this function. private function api_call($url) { $result = null; // end result // Create a new curl handle. $ch = curl_init(); curl_setopt($ch , CURLOPT_URL, "https://" . $url . "?api_key=" . __RIOT_API_KEY__); // set the URL curl_setopt($ch , CURLOPT_RETURNTRANSFER , true ); // return the transfer as a string of the return value curl_setopt($ch , CURLOPT_SSL_VERIFYPEER , false ); // turn off ssl certificate verification // Execute the api call $response = curl_exec($ch); // Get info to analyze the result $ci = curl_getinfo($ch); $httpcode = $ci["http_code"]; // If a curl error occured if(curl_errno($ch) || ($httpcode != "200")) { $die = "Curl Error Code: " . $httpcode . "<br/>"; $die .= "Curl Error Message: " . curl_errno($ch) . "<br/>"; $die .= "Curl URL: " . $ci["url"] . "<br/>"; die($die); } else { // Check if the api call we made was valid $response = json_decode($response, true); // If our response is an array check if it's an error response if(is_array($response)) { $error_key = "status"; if(array_key_exists($error_key, $response)) { $er = $response[$error_key]; $die = "API Error Message: " . $er["message"] . "<br/>"; $die .= "API Error Code: " . $er["status_code"] . "<br/>"; die($die); } } // Our response is a valid object $result = $response; } private function sanitize_url($url) { // removes all whitespaces return trim(preg_replace( '/\s+/','',$url)); } private function regional_endpoints() { static $regionini; if(is_null($regionini)) $regionini = parse_ini_file(INI_REGIONAL_ENDPOINTS, true); return $regionini; } private function region_host($shortcode) { /* * regionalendpoints.ini * @since 1.0 * * [SHORTCODE] * Description=<region_description> * Host=<host_url> */ return $this->regional_endpoints()[strtoupper($shortcode)]["Host"]; } public function region_description($shortcode) { /* * regionalendpoints.ini * @since 1.0 * * [SHORTCODE] * Description=<region_description> * Host=<host_url> */ return $this->regional_endpoints()[strtoupper($shortcode)]["Description"]; } public function api_object_by_name($name, $region) { /* * @Description: Get summoner objects mapped by standardized summoner name for a given list of summoner names. * * * @Returns: Map[string, SummonerDto] * * Object * ------------------------------------------------------------------------------------------------------ * Name Data Type Description * ------------------------------------------------------------------------------------------------------ * id long ID. * name string Name. * profileIconId int ID of the summoner icon associated with the summoner. * revisionDate long Date summoner was last modified specified as epoch milliseconds. * Level long Level associated with the summoner. */ $api_url = "%s/api/col/%s/v1.4/obj/by-name/%s"; return $this->api_call(sprintf($api_url, $this->region_host($region), strtolower($region), $this->sanitize_url($name))); } }Class that acts as the middle man between the api and the front end. Currently how it is set up it handles an internal queue. <?php include dirname(__FILE__) . "\\class-riotapi.php"; define( "SUMMONER_NAME" , 0 ); define( "SUMMONER_ID" , 1 ); class Summoner { private $riotapi = null; private $summoner = null; private $arr_summoners = null; private $region = null; public function __construct() { // Create our riot api object $this->riotapi = new RiotAPI(); } public function summoner_exists($summoners, $region, $type = SUMMONER_NAME) { static $eoa; // end of array // If our array of summoners is empty or we have reached the end of the array. if( empty($this->arr_summoners) || $eoa ) { // Get an array of summoner information from the riot api based on the type of information // supplied. switch($type) { case SUMMONER_NAME : $this->arr_summoners = $this->riotapi->api_summoner_by_name($summoners, $this->region = $region); break; case SUMMONER_ID : $this->arr_summoners = $this->riotapi->api_summoner_by_id($summoners, $this->region = $region); break; } // If our array of summoners isn't empty. if( !empty($this->arr_summoners) ) { // Set our current summoner the first element in the array. $this->summoner = reset($this->arr_summoners); } else { // We failed to acquire any summoner information so return false. return false; } $eoa = false; } else { // If we have not reached the end of the summoners array set our current // summoner to the next element. $next = next($this->arr_summoners); // Have we reached the end of the array? if( $next ) { // No. Set our current summoner to the next element. $this->summoner = $next; } else { // Yes. Set our end of array variable to true. $eoa = true; // End the loop return false; } } return true; } public function summoner_id() { return $this->summoner["id"]; } public function summoner_name() { return $this->summoner["name"]; } public function summoner_profile_icon_id() { return $this->summoner["profileIconId"]; } public function summoner_last_updated() { return $this->summoner["revisionDate"]; } public function summoner_level() { return $this->summoner["summonerLevel"]; } public function summoner_mastery_pages() { return $this->riotapi->api_summoner_masteries($this->summoner_id(), $this->region)[$this->summoner_id()]["pages"]; } }Functions.php file that is a collection of functions that echo out information. <?php require_once "settings.php"; include DIR_INCLUDE . "class-summoner.php"; function summoner_exists($summoners, $region = "NA", $type = SUMMONER_NAME) { global $cs; if(!isset($cs)){ $cs = new Summoner(); } return $cs->summoner_exists($summoners, $region, $type); } function summoner_name() { global $cs; if(isset($cs)){ echo $cs->summoner_name(); } } ?>index.php - Example of how I'm currently using the functions.php file. <?php include "functions.php"; ?> <html xmlns="http://www.w3.org/1999/xhtml"> <body> <?php while(summoner_exists("cyllo")) : ?> <div>Summoner Name: <?php summoner_name(); ?></div> <div>Summoner ID: <?php summoner_id(); ?></div> <div>Summoner Profile icon ID: <?php summoner_profile_icon_id(); ?></div> <div>Last Updated: <?php summoner_last_updated(); ?></div> <div>Summoner Level: <?php summoner_level(); ?></div> <div> <?php mastery_pages(); ?> </div> <?php endwhile; ?> </body> </html> Similar TutorialsThis topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=321687.0 Hi
so i've been learning php for 3 mouth now by reading php 6 Bible and watching lynda and so on...
i was looking for a job in few past weeks and i found out i don't have that kind of self confidence to go for it ! you know when they say : PHP Project Manager , it scar's me...
the thing is , i know all about basic to medium php , array...MySQL....all those essentials but i don't know what do they want from a php web developer .
so i began to search for intern job somewhere and i told myself i should bust my ass 24/7 for few mouth and after that i ll be real php guy and it seems like there is no place to reach not php but almost all programming languages
a year ago i was searching for the same thing but in networking section and there was 100's of intern ship jobs but in programming there is none !
so i want some one to give me (us) simple to pro real life projects .
what do they want php junior or senior developer's for ? what do they do?
what is the most common needs ?
what is the most essential things to know?
what is a hired php developer should do in the office?
some people doesn't need you in the office and want you to work from home , they give you project's , what's that?
is there any source in the web to offer what is need ?
i know its too much , but this was my last option , so if anyone can help i would practically owe him/her my whole future salaries...
Is it okay to post projects for hire in here? I have about a dozen small tasks I need done. Jared Hey folks,
I'm looking for an open-source php project to contribute to. I'm not looking for a really well-known project (ex: Wordpress, Zencart)
Something small would be greatly appreciated!
Hi, everyone.
I'm having some trouble finding tutorial projects for PHP Functions. Can anyone point me in the right direction if you know of any? I apologize if this is the wrong category to post in for my particular question.
My website is http://www.infotechnologist.biz.
We handle Web Site Development, web app development, and mobile development. No project is too big, or too small.
Contact me today with details.
My number is 4049390637.
Hi, I am developing a large management/CRM system for my company. I would like to hear your thoughts on what is the best way to organise functions and files. I know of a few ways: 1. having all your PHP at the start of each page which fetches all the data from the DB and then echo it out into the right places in that page, e.g. fetching a list of options then later echoing out the option data into a 'select' tag, creating a dynamic list. 2. Have the majority of the PHP completely seperate from the page in a seperate page, and you INCLUDE that at the start of your html page. 3. Have many seperate PHP files that do different bits for that page, e.g. one php file is for fetching a list of sales contacts, another for fetching enquiries numbers etc and have it all injecting into the correct containers on your page using Jquery and AJAX, which lets you have dynamic updates if you stick them in a setInterval loop. 4. This is the one I most fancy. You have one PHP file that has several 'modes'. Now when you call it in an AJAX statement, you pass a mode variable to it which is the condition for one of the IFs in your PHP files. So if I wanted to fetch an up to date contact list every x seconds, I would also pass a variable like 'FETCH_CONTACTS' i.e.: $.post('record-control.php', {targetCustomer:thidId, mode:'FETCH_CONTACTS'}, function(data){$('#targetDiv').html(data)}) ; Which way would you prefer if it was you? I'm developing a REST API for a website. As far as I know, the rules for RESTfulness are sort of broad. I'm just wondering if there are any good resources with tighter guidelines to developing a good, useable API. What are the common practices etc. Some of the things I'm unclear on a Should it use GET and POST, or just one of them? From what I've read about HTTP, GET is a "safe method" and shouldn't allow data to be changed on the server. Should we use GET to retrieve data off the server, and POST to save data to the server? Or is it common practice to use POST for getting and storing data? Should we utilize the HTTP status codes? Should the HTTP status change when things go wrong? Should it be 400 if something doesn't work properly? Or 404 if the method doesn't exist? If the request is successful, and there's no data to return, should it be 204 No Data or 200 with JSON/XML that shows it was successful? Hi guys, I am using Domdocument for parsing xml, i am concerned about the impact of the performance on using this Domdocument. what are the best practices to reduce the impact performance using Domdocument ? Please share your ideas. Thanks I want to add a search feature to my site so that users can search for videos. Let's say that a user conducts a search and I GET their search query: $squery = isset($_GET['query']) ? $_GET['query'] : '';Now what should I do? What are the best practices to ensure the security of my database and to provide the most relevant results to the user? Here's what I've got so far. // Make sure a search query was entered. if($squery == '') { echo "<p>You didn't enter a search query.</p>"; } // Strip HTML tags. $squery = strip_tags($squery); // Trim white space. $squery = trim($squery); // Set minimum query length. $min_length = 3; // Make sure query length is more than minimum. if(strlen($squery) < $min_length) { echo "<p>The search query you entered is too short. The minimum number of characters is ".$min_length.".</p>"; } // Connect to MySQL. // Select database. // Escape search query. $squery = mysql_real_escape_string($squery); // Break query into keywords. $keywords = explode(' ', $squery); // Count number of keywords. $no_of_keywords = count($keywords); // If just one keyword, then build statement. if($no_of_keywords == 1) { $sql = "SELECT whatever FROM `video_table` WHERE (col1 LIKE '%.$squery.%' OR col2 LIKE '%.$squery.%')"; } // If multiple keywords, then build statement. else { $sql = "SELECT whatever FROM `video_table` WHERE "; for($i = 0; $i < $no_of_keywords; $i++) { $sql .= "(col1 LIKE '%.$keywords[$i].%' OR col2 LIKE '%.$keywords[$i].%')"; if($i < $no_of_keywords) { $sql .= " OR "; } } } // Run mysql query. $raw_results = mysql_query($sql, $con); // Put results into an array for later use. $results = mysql_fetch_array($raw_results);Can this code's security be improved? How can it be altered to provide more relevant results? Should I omit words such as "to" and "the" from the query? If so, how do I do it? Should I remove punctuation? As always, I appreciate your help. You guys have taught me LOADS! Edited by Fluoresce, 06 November 2014 - 05:21 PM. I had general question about security in php. Suppose i have a value submitted from a form called $form that would go to the database. What functions would good to clean it before it goes to the database. Suppose I want to display the $form variable in the browser, what would i use to display to prevent javascript or html injection other than strip_tags. On another note, what security practice should i follow when dealing with sessions? Hello,
Can you guys point me to something where I can follow some tutorial or something and learning CI?
I've already made tons of 'Cars' models... 'Dogs' .. 'Cats'.. etc but I really need some project where I can follow steps to creat and learn while I create.
p.s. I think I post this thread in right place but please correct me if is wrong.
Thank's!
This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=359016.0 I must confess, I've not really done much unit testing at all in the last 3 years. Can anyone give me an idea of what they would test and why that would be faster or more efficient than running the code as a user? One area I can see it having huge benefits is when I'm testing methods which interact with a database, like user registration, which I would probably test by registering several times - fixing any bugs, making amendments and repeating. Ok, so I kinda sold the idea to myself there But, what about for small applications? I've seen people testing whether a variable is countable...why would I not just check the output immediately? Appreciate any advice. To execute code on successfully submitting text input, is this "bare minimum" code secure enough?
if(!empty($_POST["textfield_input"])) { ...or is it best to make sure all 4 of these are confirmed:
if (
The html portion is simply: I've searched on the net about this several times, and see different answers, and it looks like each PHP expert has their favorite.... but I would rather know the "best practices" answer to this. Thank you!!
Edited November 5, 2019 by StevenOliver This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=343169.0 Scenario: My page generates several PHP variables. Some of those variables get posted to another page. Question: If a variable is to be assigned to a Session, is there any reason to assign this value to a regular PHP variable? Example: When an API generates a "shipping label tracking number, which is better, "A" or "B" or subtle variation "C":
A.) ... and then use $_SESSION["trackingNumber"] throughout the rest of my script (like this: echo "Hello, here's your tracking number: ".$_SESSION["trackingNumber"]).
B.) ... and then use "$trackingNumber" throughout the rest of my script (like this: echo "Hello, here's your tracking number: ".$trackingNumber).
C.) ... and then use "$trackingNumber" throughout the rest of my script (like this: echo "Hello, here's your tracking number: ".$trackingNumber). Thank you! I've always wondered about this. Which is best?
This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=351660.0 Proportionally scale image - imagecopyresampled() This is part of a function I have to upload images and create thumbnails from the stored image - '$stored_image' Code: [Select] $src_image = imagecreatefromjpeg($stored_image); // $src_width = imagesx($src_image); $src_height = imagesy($src_image); $new_width = 85; $new_height = 85; // if($src_width > $src_height){ $thumb_w = $new_width; $thumb_h = $src_height*($new_height/$src_width); } if($src_width < $src_height){ $thumb_w = $src_width*($new_width/$src_height); $thumb_h = $new_height; } if($src_width == $src_height){ $thumb_w = $new_width; $thumb_h = $new_height; } // $thumb = imagecreatetruecolor($thumb_w, $thumb_h); imagecopyresampled($thumb, $src_image,0,0,0,0,$thumb_w, $thumb_h, $src_width, $src_height); imagejpeg($thumb, $stored_thumb, 100); imagedestroy($src_image); imagedestroy($thumb); }else{ The images are different size and orientations, landscape and portrait. The thumbnails need to have the same height so I need to proportionally scale the images How can I proportionally scale images so the thumbnails have the same height I'm really stuck here so any help would be greatly appreciated. |