PHP - Refactoring Question
I have a class that adds a special PDF page to an existing PDF. The page refers to a specific product and there are products A, B, C, D. Products B, C, D are similar and with a bit of if/then/else magic I can basically reuse the same function for all 3, but product A is different enough to have its own function.
My class looks like this:
class AddPdfPage { function addA(&$pdf, $vars) {} function addB(&$pdf, $vars) {} function addC(&$pdf, $vars) {} function addD(&$pdf, $vars) {} } //The way I call it from within the code right now is like this: AddPdfPage::addC($pdf, $vars); AddPdfPage::addB($pdf, $vars); //the variable below contains the product line -- A, B, C, or D //that's the one I said I could use to merge functions B/C/D into one if I wanted to //I could even include product A if I wanted to even though the code there is different. $vars['productLine']; //The code inside addX() functions is something like: function addX($pdf, $vars) { $pdf->addPage($vars); $pdf->addDescription(".."); //that is different based on each specific product line }Assuming I want to add a page to PDF for a paricular product X, how do I write or structure my code? I am not exactly sure. Do I set it up somehow to use polymorphism? Do I do something else? I assume I don't really want to merge products B/C/D into the same function, even if I could, since they physically represent different product lines, so I might as well keep them as such -- separate. But I may want to use some features of the language to clean up and better up my code. The "how", and what techniques do I use, and what my final code may look like is what my post is about. I am thinking of doing something like: class AddPdfPage() { private $pdf; private $vars; private $productLine; function __construct($pdf, $vars) { $this->pdf = $pdf; $this->vars = $vars; $this->productLine = $vars['productLine']; } public function addPage() { switch($this->productLine) { case 'A': ...break; case 'B': ...break; case 'C': ...break; case 'D': ...break; } } }Use that as a jump start and I guess I could use polymorphism by creating separate classes for each product line and extending some base class, if switch statement is not good.. (http://c2.com/cgi/wi...StatementsSmell) but I feel like I will be polluting my file system with too many classes and not sure if that's exactly a benefit. So just thinking about how to do this. Edited by dennis-fedco, 15 October 2014 - 10:56 AM. Similar TutorialsImagine 6 PHP classes (one each for a product line), that have very similar coding structures, that go like this:
//function that computes stuff inside each of 6 files: //they vary slightly from file to file but essentially it is this: function computeFunction { $this->x = new X(); $this->x->calcD(); if ($this->x->dOk) { $this->x->calcE(); $this->x->calcN(); } //more complicated logic that is essentially like above //and by the way! print $this->x->someVarThatIsUsedLater; }Then there is a single class like so : class X { function calcD() { //compute some condition if (<computed condition is met>) $this->dOk = true; else $this->dOk = false; //and by the way $this->someVarThatIsUsedLater = 4; } }Just to bring your attention to it, none of these functions return any result or value, but they nevertheless operate on variables of key interest via side-effects. That is, they modify variables that essentially act like globals, and then use those variables later ($this->dOk and $this->someVarThatIsUsedLater are one more prominent examples). I need to untangle this mess. And make it clean and clear again, and make sense. How do I best proceed? I have been wrestling with some ideas... like $this->dOk, can within reason be turned into a return variable of calcD() function, and then be tested against like if ($this->x->calcD()) and I think it will be reasonable enough. But then there are other functions that don't return anything and just act on variables via side-effects anyway so $this->dOk is one of the lesser troubles... Other than that, what I am thinking of doing is getting rid of these mini-functions (calcE(), calcN(), etc.), removing them as a funciton, and putting their body directly into the code, as a first step to refactor. Many of the computations done inside are just a few lines of code anyway, and the functions kind of hide a lot of side-effects that happen, instead of actually encapsulating the behavior. So while it may be counter-intuitive to dismantle the functions that appear to be doing something that normally can be encapsulated (computing key variables E, N, etc), I think dismantling them will actually clean things up as far as collecting all the side-effects inside a single parent function thereby making them more visible. Caveat: while doing so I will end up with 6 copies of untangled dismantled functions, because dismantling class X and putting its content into each of the 6 product line classes will have that effect. But my hope is that from that point I will see more clearly to start identifying places where I can start to truly encapsulating the behavior via various structures, instead of masking it. Problems / Questions: I would like to but I am not entirely sure that I can skip that step of dismantling functions & the 6x multiplying effect. It's probably the same like skipping steps in solving polynomial equations. Some can do it and some need to list each step of their work. And I am not entirely sure what structures I can replace it with in the end after I dismantle the functions. It also looks like a lot of work. Is there a better way? P.S. I already put tests on computeFunction() for each product line so I can be less paranoid about hacking stuff up. Edited by dennis-fedco, 19 January 2015 - 03:06 PM. Hi all I have some code I'd like to re-factor Code: [Select] <?php $question_1 = $form->getObject()->getQuestion1(); $question_2 = $form->getObject()->getQuestion2(); ?> <div class="admin"> <div> <?php echo $form['question_1']->renderLabel(); echo $question_1; ?> </div> </div> <div class="adminl"> <div> <?php echo $form['question_2']->renderLabel(); $q2 = str_replace("-", '<br />',$question_2); echo $q2; ?> </div> </div> I'd preferably like some kind of for loop, that will just increment the _1, _2 values. Can anyone offer some help? Thanks Hi I have the following code: $image_1 = $value->getElementsByTagName("Image1"); $image1 = $image_1->item(0)->nodeValue; $image_2 = $value->getElementsByTagName("Image2"); $image2 = $image_2->item(0)->nodeValue; $image_3 = $value->getElementsByTagName("Image3"); $image3 = $image_3->item(0)->nodeValue; $filename_1 = basename($image1); $ch = curl_init ($image1); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_BINARYTRANSFER,1); $rawdata=curl_exec ($ch); curl_close ($ch); $fp = fopen(Mage::getBaseDir('media') . DS . 'import/'.$filename_1,'w'); fwrite($fp, $rawdata); fclose($fp); $filename_2 = basename($image2); $ch = curl_init ($image2); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_BINARYTRANSFER,1); $rawdata=curl_exec ($ch); curl_close ($ch); $fp = fopen(Mage::getBaseDir('media') . DS . 'import/'.$filename_2,'w'); fwrite($fp, $rawdata); fclose($fp); $filename_3 = basename($image3); $ch = curl_init ($image3); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_BINARYTRANSFER,1); $rawdata=curl_exec ($ch); curl_close ($ch); $fp = fopen(Mage::getBaseDir('media') . DS . 'import/'.$filename_3,'w'); fwrite($fp, $rawdata); fclose($fp); Would someone help me to refactor this, as I can seem needing $image_4, $image_5 at a later date. Thank you Hi I have a method, which is pretty large. It has a lot of 'duplicate' code and I'd like to refactor it: protected function doSave($con = null) { $choices_1 = $this->getValue('question_1'); $choices_2 = $this->getValue('question_2'); $choices_3 = $this->getValue('question_3'); $choices_4 = $this->getValue('question_4'); $serialized_ = ""; $first = true; foreach($choices_1 as $choice_1) { if(!$first) { $serialized_1 .= ","; } $first = false; $serialized_1 .= $choice_1; } foreach($choices_2 as $choice_2) { if(!$first) { $serialized_2 .= ","; } $first = false; $serialized_2 .= $choice_2; } foreach($choices_3 as $choice_3) { if(!$first) { $serialized_3 .= ","; } $first = false; $serialized_3 .= $choice_3; } foreach($choices_4 as $choice_4) { if(!$first) { $serialized_4 .= ","; } $first = true; $serialized_4 .= $choice_4; } $this->setValue('question_1', $serialized_1); $this->setValue('question_2', $serialized_2); $this->setValue('question_3', $serialized_3); $this->setValue('question_4', $serialized_4); return parent::doSave($con); } You can see most of the arrays have a '_1', '_2' after them, the same goes for the $serialized variables. What I'd like is to maybe have some kind of loop, that will reduce my code down, and rather than me typing all the code above, possibly increment the '_1', '_2' part upto the 5 iterations. Can anyone provide some help/code for me to carry this out? Regards I was working on this project earlier on in the year, I have not posted here much. I would like to get it over with and start something else. I have other files which look like the excerpt of code from a file below. I personally think that my code lacks structure and could be organized in a better fashion. I lost most of my progress and am having to backtrack and restore code. Is there a way to re-write this code and make it more readable? Please and thank you!
<?php include('header.php'); require_once('dbcon/dbcon.php'); //include('functions.php'); if ($_SERVER['REQUEST_METHOD'] == 'POST') { // sanitize values before entering them into db, no bad seeds. $username = mysqli_real_escape_string($conn, $_POST['username']); $password = mysqli_real_escape_string($conn, $_POST['password']); $bio = mysqli_real_escape_string($conn, $_POST['bio']); $hashed_password = mysqli_real_escape_string($conn, password_hash($password, PASSWORD_DEFAULT)); $email = mysqli_real_escape_string($conn, $_POST['email_address']); $confirmation_status = 0; /* function sanitizeValues($x, string $postString) { $x = mysqli_real_escape_string($conn, $_POST[$postString]); }*/ $username_query = "SELECT * from profiles001 WHERE username='$username'"; $result = mysqli_query($conn, $username_query); // if username exists do not continue... if (mysqli_num_rows($result) > 0) { header('Location: /soapbox/signup.php'); // let user know that username is taken... } else { // file upload stuff... $file = $_FILES['file']; $fileName = $_FILES['file']['name']; $fileTmpName = $_FILES['file']['tmp_name']; $fileSize = $_FILES['file']['size']; $fileError = $_FILES['file']['error']; $fileType = $_FILES['file']['type']; $fileExt = explode('.', $fileName); $fileActualExt = strtolower(end($fileExt)); $allowed = array('jpg', 'jpeg', 'png'); // avatar file constraints checks... if (in_array($fileActualExt, $allowed)) { if ($fileError === 0) { if ($fileSize < 1000000) { $fileNameNew = uniqid($_SESSION['username'], true) . "." . $fileActualExt; $fileDestination = 'uploads/' . $fileNameNew; move_uploaded_file($fileTmpName, $fileDestination); } else { echo "Your file is too big!"; } } else { echo "There was an error uploading your file" . $fileError . $fileSize; } } else if (!(empty(in_array($fileActualExt, $allowed))) && !($allowed)) { echo "Cannot upload file of this type!"; } mkdir("channel/" . $username); mkdir("channel/" . $username . "/videos"); fopen("channel/" . $username . "/index.php", "w"); $account_open_date = date("Y-m-d h:i:s"); $current_date = date("Y-m-d h:i:s"); //$account_open_date_retrieval_sql_select = "SELECT account_open_date from profile0"; //$account_age = date_diff($row, $current_date); // acct open date - current date = account age //$account_age_result = mysqli_query($conn, $account_open_date_retrieval_sql_select); //$row = mysqli_fetch_assoc($account_age_result); // if-then-else-if statement to get rid of the fileDestination var undefined error when avatar photo is not submitted.... if (!(empty($fileDestination))) { $sqlinsert = "INSERT INTO profiles001 (username, password, email, c_status, doc, avatar, bio) VALUES ('$username', '$hashed_password', '$email', '$confirmation_status', '$account_open_date', '$fileDestination', '$bio')"; } else if (empty($fileDestination)) { $fileDestination = "assets/soap.jpg"; $sqlinsert = "INSERT INTO profiles001 (username, password, email, c_status, doc, avatar, bio) VALUES ('$username', '$hashed_password', '$email', '$confirmation_status', '$account_open_date', '$fileDestination', '$bio')"; } $result = mysqli_query($conn, $sqlinsert); } } ?> This will be somewhat of a brain dump with somewhat vague questions. To summarize it right now, something about "refactoring software" has been bugging me. The length of the process, the work it takes, and the time, and the "no immediately visible results" that it produces.
There have been numerous questions on "do I refactor or rewrite". Depending on circumstances, one choice may work better than another, although historically for working projects (projects people are using continuously), refactoring seemed to do better, since it does not break things as much as rewriting does. And when things break all at once, such as when introducing a rewrite (which most likely has different behavior, UI, feel, workflow, etc. etc.), people tend to get upset. Well, refactoring seems to smooth out the 'upsetness' over a much longer period of time. People change as software changes, and each change is not as abrupt as with a rewrite. There are books written about refactoring software. That process takes time and work, `while not changing the functionality of the software`. Little improvements can be done here and there, but the main point becomes improving the internals of the software without affecting the outside behavior, the user experience. From the business end, *there are no changes!*. We have developers *doing busy work* without showing anything to the business, until perhaps much later. Is that bad? Where I work, I have business people scoff at "what have we been doing" quite regularly, and saying things like "add convertion from one unit system to another? Just put it in!" Which ends up me staring into vastness of legacy code and taking 2-3 weeks to "put it in", what in someone's mind takes a day at the most. But that's cuz maybe I'm slow, but I chose to refactor relevant code first, at least moving View items into respective view containers as a first step. What is the purpose of refactoring software? What, per se does it make better? What expectations can be set? What do I do next time someone says "it is taking too long", other than saying ... cuz I am refactoring! I am refactoring entire collective scattered SQL from my legacy codebase, and into separate classes, and looking for some structure to put it into. Right now I have folders effectively called `DataFromDB` - contains classes that accepts whatever parameters are given, and returns pure data back to the user `DAO` - Data Access Object, which takes that raw data from DB and makes sense out of it and prepares it for consumption by the model/business logic layer objects. That is: - src (folder) |- DAO (folder) | - ProductADAO (classes - take data in, return consumable objects out) | - ProductBDAO | - ... | - ProductZDAO |- DataFromDB (folder) | - ProductAData (classes - contain methods to query pure result sets from DB) | - ProductBData | - ... | - ProductZDataWhenever I need to make a new SQL or refactor an old one I do this: What is this SQL doing? Is it operating on `SomeObjectX`? If yes, find/create class called `ObjectX`, and add a method to it, extracting pure data from DB, put it into `DataFromDB` folder. Write the `DAO` object if needed to transform data into a consumable object. Use the object as is in my code. Does this look like a good strategy? Is there a better one? My problem with this one is that before (now) all the SQL is tightly coupled and is included into the multiple business classes. Using the above strategy will mean I am to be creating many many classes, a lot of classes, most likely one for every few SQL statements. The pros is that it seems like I will achieve a level of code modularity that I wanted. when in a form, I wish to build a conditional that if the response to a radio button is a value of 2 (female), it will display an input requesting for users maiden name. If not 2 goes to the next input statement. Here is code I was experimenting with: <html> <body> <form action="" name="test" method='POST'> <input type="radio" id="sex" value=1 checked><label>Male</label> <input type="radio" id="sex" value=2><label>Femaleale</label> <?php $result = "value"; if ($result == 2) echo "<input type='int' id='gradYear' size='3' required>"; else echo "Not a female!" ?> <input type="submit" value="GO"> </form> </body> </html> The code passes debug, however, Not a Female is displayed. My question is - Can I do this and if so, what value do I test against id='sex' or value. I tried each one but gave the same results. I realize that $_POST[sex] would be used after the submit button is clicked. But this has me stumped. Thanks for the assis in advance. Sorry for the really, really basic CSS question. (I'm asking this in the PHP forum, because so far, you've all been nice to me and haven't made fun of some of my really dumb questions.)
i am trying to understand, how a site like ebay can display content and be case insensitive? for example: The original url: http://www.ebay.co.uk/itm/Toshiba-Satellite-C50-AMD-E-Series-1-4GHz-Dual-Core-15-6-Inch-500GB-2GB-Laptop/151458954958the above works fine and go to the intended page. user editing the browser url into lowercase : http://www.ebay.co.uk/itm/toshiba-satellite-c50-amd-e-series-1-4ghz-dual-core-15-6-inch-500gb-2GB-laptop/151458954958random uppercase and lowercase. http://www.ebay.co.uk/itm/toshiba-sateLLite-c50-aMd-e-sERIes-1-4ghz-dual-core-15-6-inch-500gb-2GB-laptop/151458954958both the urls above also work fine and go to the intended page. How can such a thing can work? it is supposed to throw an error such as page not found and the like? any thoughts welcome. Hello, i am currently working on a project and i have been on google and nothing has helped i am trying to detect characters in the URL so for example XSS if someone typed in the URL:
home.php?=<script>document.cookie();</script> OR home.php?=<?php echo file_get_contents("document.txt", "a");How would i be able to make a kind of firewall to detect this? and if it does then redirect to another page. Thanks. Code: [Select] /*** a new dom object ***/ $dom = new domDocument; /*** load the html into the object ***/ @$dom->loadHTML($file); /*** discard white space ***/ $dom->preserveWhiteSpace = false; /*** the table by its tag name ***/ $tables = $dom->getElementsByTagName('table'); /*** get all rows from the table ***/ $rows = $tables->item(0)->getElementsByTagName('tr'); /*** loop over the table rows ***/ foreach ($rows as $row) { /*** get each column by tag name ***/ $cols = $row->getElementsByTagName('a'); /*** echo the values ***/ echo $cols->item(0)->nodeValue.'<br />'; } Hi, Is there a way to start to echo from 43? thanks. Major breakthrough. utf8_encode() allows me to view utf-8 characters in the browser. Therefore, my source data file must be ISO-8859-1 encoded text, right? Am I understanding this correctly?
<?php //mb_internal_encoding("UTF-8"); header('Content-type: text/html; charset=utf-8'); $file = fopen('some_csv_file_created_by_excel.csv', "r"); ob_start(); while (($spec = fgetcsv($file, 100000, ",")) !== FALSE){ echo($spec[0].' '.utf8_encode($spec[0]).'<br>'); } $string=ob_get_clean(); ?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>utf</title> </head> <body> <p><?php echo($string);?></p> </body> </html> Edited by NotionCommotion, 11 January 2015 - 08:22 PM. i have took a test that i think it has some errors: can you please confirm or infirm that A is the right answer? Question: The default value for __FILE__ is _______________________________. A. the complete path of the currently executing script B. the relative path of the currently executing script C. a magical constant; it does not have a default value D. the complete path of the previous executed script E. the relative path of the previous executed script Correct Answer: C User Answer: A Explanation: The PHP engine stores the full path and filename of the currently executing script within the __FILE__ constant. I am trying to make it so that it will load if the site if the site is online(EG. $siteonline = 1), and so on. I can't seem to think of how I could do this so it will work from the very top of the page's html, to the very bottom. Like the following code is meant to list all of the stuff in that database. <?php $list_q = mysql_query("SELECT * FROM settings") or die (mysql_error()); while($list_f = mysql_fetch_assoc($list_q)) { } ?> I have my page laid out like this.. <?php include "includes/connect.php"; include "includes/config.php"; ?> <?php $list_q = mysql_query("SELECT * FROM settings") or die (mysql_error()); while($list_f = mysql_fetch_assoc($list_q)) { ?> Html content etc.. <?php } include 'includes/footer.php'; ?> But if I do it that way, It only displays what is in footer.php. On my login page i have a set a session when the user logs in called loggedIn and it = true
if($count == 1) { $_SESSION['username']; $_SESSION['password']; $_SESSION['loggedIn'] = true; header("Location: index.php");and on my index page i have session_start(); if(!isset($_SESSION['loggedIn'])) { echo "You are not currently logged in and to view this page you must be logged in to have access."; die(); }but when the user logs in it comes up with the message above echo "You are not currently logged in and to view this page you must be logged in to have access."; which obviously it should not do. Does anyone know how i can fix this? hi php people, I am wondering will if the code below will work when I call $C->getafoo() will I get foo; I keep getting an error at this point return $this->A->a(); saying the method is not there Code: [Select] class A{ public function a(){ return "foo"; } } class B { public $A; function __construct($A) { $this->A = $A; } public function geta(){ return $this->A->a(); } } class C extends B{ public function getafoo(){ return geta(); } } $C = new C(new A()); echo $C->getafoo(); I'm creating a re classified ad site and I've hit a brick wall. I'm trying to create a 'listing' which will contain info and pictures of the property that's for sale, but I'm unsure on how to do it. Would I have to create different db tables to have the albums, images and listing together? Or would can I just do it all in one table? I appreciate your help. Just get started with OO in PHP. If I create an object while on one page and then call another page, can I still access that first object, or is it destroyed when the second page is called? For example, if I have on page1.php: Code: [Select] $obj = new $MyObject(); and then call page2.php, is it possible to still access $obj while on that page? I'm considering getting a VPS, but I'm not entirely sure what this would be able the handle. The specs doesn't look that good to me, but my friend swears it will handle running apache/php/mysql handling large websites and databases without a problem. I want to run multiple databases that just store statistics and I'm a bit worried about the RAM and the company doesn't even mention a cpu. Here's the specs: 256MB RAM 300GB HDD 10Mbps unmetered 1 IP Address My friend runs two counter-strike: source servers off his VPS (same stats).. so I'm actually considering this, but it just seems like it's not powerful enough. Oh.. forgot the most important part.. it's only $9. |