Jump to content

dennis-fedco

Members
  • Posts

    77
  • Joined

  • Last visited

Everything posted by dennis-fedco

  1. Yes ... I am not entirely sure if the first approach will work since there are more than a few lines of code to figure the View Template out, and those lines of code include some "business logic" as well. For example part of $input is a boolean $isMotorPresent, and other engineering type values. Part of generated $output is "How many supporting stands does this product have" which take some hefty computation to figure out. "presence of motor" is not part of $output, although I suppose it could be.... That's kind of a judgement call. Both pieces (from $input & $output) are needed to pick the right View template. So a problem remains.. My particular View and the way my code is currently set up, my "View Factory" or my "Code that's close to the controller", needs to know $input as well. So, for example I would have to do this: $this->view = ClassThatCreatesViewsFromOutputData::factory($input, $output); Or I would have to copy certain values from $input to $output so I can do this: //whether $output is bloated I guess is relative, I can say it's not.. //But the bloated part (one copied over as pass-through from $input) will only used to compute the View template //and will not be used otherwise. $this->view = ClassThatCreatesViewsFromOutputData::factory($bloated_Output_That_Contains_A_Bit_Of_Input); And that was my problem .... i.e. I can either 1. put up with using both $input and $output in my code in my View Factory (or make the $output contain $input) 2. compute part of View (the template part) inside my ClassThatComputesData, probably breaking SRP, because ClassThatComputesData already contains $input and the view-template-required $output is being created as part of ClassThatComputesData 3. make View-template accept $input only and recompute the needed $output vars All of the above will work but I think is somehow breaking SRP or at least creating some bloat/rework........ #2 is how my legacy code was, and my current code is a little weird because I essentially do array merge .... which I see as a hack $this->view = ClassThatCreatesViewsFromOutputData::factory(array_merge($input, $output));
  2. I have some code that takes "User Input", then does a series of computations and produces "Output Data" to be displayed on a PDF document. PDF document is a template that is subsequently displayed with data superimposed onto it in the appropriate places. One complication is that PDF document is a template, and template file name itself depends in part on data from the "User Input" and part from the computed "Output Data". In original (legacy) code, PDF template file name is embedded into "Output Data". So I could do $outputData = $this->computeOutput($userInput); $pdf = new Pdf(); //$outputData['template'] == 'computed_pdf_filename.pdf'; $pdf->setTemplate($outputData['template']); $pdf->superimposeData($outputData); My question is ... do I separate computation of the PDF template (which does not have much to do with outline data) from computation of the outline data? They both share a good chunk of transient variables to compute things. so in some ways it makes sense to keep "PDF template" as part of "Output Data". But on the other hand, what if I later decide to not use PDF at all but to use PNG Images? Or TIFF? Or some other format? Unlikely, but then I will need to rip out my PDF-Template computing code from "ComputeOutput" method. But the to compute Template Filename I will need to pass that function both the input and the output. Something like so $outputData = $this->computeOutput($userInput); //if I separate it out $template = TemplateService::computeOutput($userInput, $outputData); $pdf = new Pdf(); //$outputData['template'] == 'computed_pdf_filename.pdf'; $pdf->setTemplate($template); $pdf->superimposeData($outputData); Back to the question ... are there any pros or cons to separating data from the template?
  3. If humans were capable of understanding most god-awful obfuscated computer code, whether it was binary, high level, or assembly, will there be a need for complex refactoring rituals, design patterns, frameworks, application stacks, and so on? I am wondering if the need to refactor code arose purely due to people not being able to comprehend, understand someone else's code. It is sometimes said that perfectly refactored code is easier to change, and maintain. While perhaps true in general, if humans were capable of comprehending code immediately upon access, no matter how horribly un-factored the code is, they will still be able to make changes to it. Even if changes in un-factored code takes 20 times as much effort (i.e pure textual code changes), it still won't take as much time as common humans take now to make changes to god-awful un-factored code. Are there any considerations that I have left out that will still make refactoring needed even if humans possessed super-human code-reading and comprehending abilities?
  4. alright. I can use DIVs and not tables. Maybe even if I do that, my life will be easier (i.e. maybe I won't have to use tabindex and such to force table to behave my way), and maybe I can choose either row or column implementation this way. What you have is promising I am going to try a few more things to make sure. My goal is basically: keep HTML simple (right now my HTML is not simple, with tabindexes and all) keep logic simple (same -- right now I have to deal with a mess of indexes and mapping them to proper columns) a new one -- being able to save the form (via AJAX), and restore the form (say I have 10 data sets, I don't want to reenter them all if I need to make a change) One way to implement that I have seen is to use AJAX to add one row at a time. So at any one time you effectively have only one form-column to deal with and you generate that form in the back and load it via AJAX. ehh there's gotta be a library for this. I am more "back-end" PHP wiz ...
  5. I want to create functionality where user can enter some data. Each data is a set of 6 variables. I want to make the number of columns dynamic and start off with a single column and make multiple columns via for example an "Add Column" button. I have started trying this concept with columns (https://jsfiddle.net/dennisfedco/vfhc1jma/5/) Or, if it makes things simpler, I can do rows. But initially, user sees 6 input boxes. Enters values. Then clicks "add new set" which shows 6 more input boxes (via column or row) and enters new values. Then user can select one of the column/row as "main" and submit. How can I do this with least amount of trouble? My goal is to make it solid and easy to debug if there is trouble, so I would like to avoid things like AJAX or making it too dynamic or too breakable. In short in my example there are 4 columns now. But I want to make it just one, and have user add more if needed.
  6. I have been playing with this a lot recently. And I thought -- Why do I have to populate Product with a Motor? I do not have to! I guess if my business application needed a Product with a Motor, as a unit, then yes, that is one way to do it. But if my application matches various combinations of Products and Motors, then I can have them be loaded separately via DataMappers. Basically whatever suits my needs. This begs for a more general question -- If I say have an object that is comprised of smaller objects, when is it appropriate to load them all up and when is it appropriate to just load them on as-needed basis. //do I end up with this class BigProductMapper { public function loadEverythingUp() { //load all subproducts into BigProduct } } //or with this class BigProductMapper { public function loadJustTheBigProduct() {} } class SubProductMapper1 { public function loadSubProduct1() {} } class SubProductMapper2 { public function loadSubProduct2() {} } ... class SubProductMapperN { public function loadSubProductN() {} } //have production code load things up as part of bigger class as-needed
  7. thanks I think I understand now and don't need any further help so far but I am curious -- what is it that's undesirable towards dependency in the current version of code that I have? namely, if I wish to change the underlying database, I do not really have to touch my object. so there is some decomposition there that works. I may not even have to change the MotorDAO or the MotorData class, and change just the db_query() function when I switch native functionality If structure of SQL changes, then I have to change MotorData. But other than that, my entitity remains intact. Or is it? What is bad about dependency in the code?
  8. At first I thought it meant "We have 64Mb free, and we tried to allocate 36 bytes in that vast free space, but there was an error", which did not make sense to me. But then I realized it means "We have been allocating memory right and left for the stuff you do in your script and all entire memory limit of 64Mb has been used up and is full. Now when your rampant script tries to allocate 36 more bytes, we just can't take any more". So increase your memory limit, or find a bug in your script that caused this high memory usage.
  9. I supose another question too is : Why use a Mapper pattern opposed to any other DB pattern available? And also I do plan to eventually (if time/resources allow) to migrate to Doctrine or similar layer
  10. Thanks I understand that I went too far, but after that I am not sure I understand the points completely. Product and Motor are my business classes. The rest is various DB-functionality and computation and display. Are you saying that my bussiness class depends on DB? Where exactly is the dependency, because I don't think I am aware of it, or I don't see it. The way Product and Motor interact are not as clear cut as I've made it appear to be and their purpose currently is more messy. So I want to focus on overall theme and not on any specific usage of the clasess. But, for example, I load motors and products separately and then run varoius simulations. There is no direct motor-product connection. More like there are "motors" and "product" and then they interact. Can you also show an example of how to use the ProductMapper? Is it just //using the mapper $products = (new ProductMapper())->someBusinessIdentifiableMethod(); //calls DB-functions directly I do not see how it is different from this (what I have now) : //what I currently have - invoking DAO->Data->Db->MySQL $motors = $this->product->motor->loadMotors(); //calls a DAO class, which calls DB functions direclty They both provide me with the same stuff - product or motor objects that were loaded from DB in some way or another... my way takes a lot more calls (various object invocations) though.
  11. I was doing various separation of concerns refactoring but I think I went too far. I think I have too many layers and want to do a reality check. Originally there was some code in the Product class that called native functionality directly. Now it's just too many layers, I think. So what I have now is: "real" business-layer code (calls) --> (i.e.) Motor class (which calls) --> DAO layer (that calls) --> Data layer (that calls) --> a global function that calls native MySql function Is there a healthier way to restructure this complexity without losing benefits of SOC and OO? class Product { ... { // business logic needs motors $this->product->motor->loadMotors(); } } //class to handle motor functions class Motor { public function loadMotors() { return $this->motorDao->loadMotors(); } } //layer to handle connection between "object" and "database result" class LoadMotorDao { public function loadMotors() { $motorDbResultObject = $this->motorData->giveMeMotors(); //some data-to-object handling code return $motorObject; } } //class that purely returns just data from DB as-is //typically a DB result set class LoadMotorData { public function giveMeMotors() { return db_query("SELECT ... "); } } //global function that calls native functionality function db_query($query, $database = "", $conn = "") { return ... mysql_db_query($database, $query, $conn); }
  12. My question is about moving my codebase to modern DB practices (with least work possible). My codebase is currently using outdated MySQL extensions. Like so: <? $sql = " SELECT description, quantity FROM sales.item WHERE id = {$orderid} "; $result = db_query($sql); for ($i = 0; $i < db_num_rows($result); $i++) { $row = db_fetch_array($result); ?> <tr> <td><?=$row['description']?></td> <td><?=$row['quantity']?></td> </tr> <? } ?> I have 1140 such statements in "SELECT" statements alone and not counting any DELETE/UPDATE or other SQL statements. This means that updating and paying attention to each statement individually is going to be a huge effort. That effort is what I want to avoid, or automate as much as possible. Question: other than leaving the codebase as-is, are there any reasonable ways to move it or nudge it to the current latest PHP DB practices? (Be it, PDO, or mysqli, or Doctrine, or otherwise), without expending herculean amount of effort?
  13. thanks.. ... in my case labels are only to be produced for certain product lines, so for example we have vetted lables for A and B only, but not C. my code (above) is placed into existing code that exposes my code to all product lines. In other words, my code sees all product lines but must only produce labels when it sees A or B (and new lines needing labels may be introduced later) So if my label-generating-code fails for reason of "no label defined for existing product line X", it is not big deal, meaning "all is well" and nothing should be looked into. Otherwise, for other errors it may be good to log a message. One thing exception handling does for me is it has a standard way to propagate the error message from a Leaf Function of the code, up the chain, to some parent function that has a catch block. Thereby saving me the work and saving me the cluttering up of my code with trying to pass such error message up the chain myself. I see your point about differentiating between Factory failing or my code failing, and I think I am going to keep the exception just becaues I already written it that way. But truly I do not think it is something that needs exception as somewhere I have read an advice that said Only use exceptions for exceptionary situation. I am tempted to say that in my case, my use case is not very exceptional. And still, despite this, using Exceptions makes my life easier in this case. If I remove exceptions, I lose the up-the-chain ability and will just end up with some logging messages. So in other words, I am still in "what am I doing" stage.
  14. I have some code that is run for multiple product lines, A, B, C. I've coded up a factory that takes product line, some data, and produces a label for that product. Currently something like this: //pseudo-codish foreach(..) { try { $x->getLabel($productLine); } catch(Exception $e) { Log::write("can't create label"); } } getLabel() takes a $productLine, which is then sent to a factory class, and if it's a new product line, the factory throws an exception as it doesn't know how to handle that product line. I am thinking that why am I writing exception for this? Why not get rid of exception throwing and exception handling code just move that Log::write() line to the place where I am currently throwing the exception (not shown) My question is thus -- Do I need to use Exception Handling in this case or do I remove Exceptions from the code? The end result is kind of the same. Except, without exception, (without doing any extra coding work to return parameters), I will essentially be unable to direct the flow of code at the higher level (such as pictured above), based on whether the product line was known or unknown to the factory.
  15. my answer .... 6 tables. Not that many. Why - to store data related to my application. I am not sure what you mean by my application already knowing the table structure. It is using the tables, so it is aware of them.
  16. I have a feature in my Web Application where I make a copy of an business object. Business object is stored in the database. The way I make a copy is a little generic and I wanted to check if I am doing it right. Namely, I use Database metadata to help me instead of using actual column names from a table. I have functionality in my DB where I use SQL statements like so: SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = 'db_name' AND TABLE_NAME = 'table_name' AND COLUMN_NAME NOT IN ('id', 'db_table_foreign_key'); it essentially selects column names from a particular table belonging to the business object, minus the keys. All I need to do to copy another table is to change the DB and table names in the above SQL. Later I use another SQL to do the actual new record creation: INSERT INTO db_name.table_name SET ... -- uses PHP code to essentially copy over things, like: {'column_name' = $value, ...} -- $value is from another SQL (not shown) that loads up values to copy foreign_key = $new_foreign_key; Where I use PHP code that uses variables from the first SQL (and actual values from another SQL which is not shown) to essentially create a new table with values copied over from old table to new table, creates new keys, and foreign keys. My question is about "am I doing this right"? I have many tables and in a way, taking a cheap way out, doing this same generic code basically to copy over several tables, instead of copying every table by using actual SQL with actual table names for each separate table. I am concerned that going to information_schema.COLUMNS is problematic, even though it saves me lots of work when tables change colum names/ new names are added, etc. I'll appreciate any insight and experience on if my approach is reasonably industry-practied...
  17. To add one important bit: class X has if-then-else statements testing for a specific product line, when using various formulas. So when dismantling functions, I will actually be porting part of the functions back to their respective product lines. Doing so still will result in duplication as some product lines use same code to do some things.
  18. Imagine 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.
  19. How strongly are you advocating this approach and Doctrine approach? My background is that currently I have 1100+ SQL statements in my code, and an average SQL merges 2-4 tables like so: SELECT * FROM a.order LEFT JOIN a.item ON a.order.id = a.item.a_order_id LEFT JOIN b.part ON a.item.b_part_id = b.part.id WHERE b.part.rp_id = $id GROUP BY a.order.id Essentially whatever method I choose that requires any change to the way I do SQL now, will require an exercise of eventually changing those 1100+ statements to use that new way. Or if I abandon it at any time I will have some bare SQL statements in my code and some Doctrinified statements in my code, and future developers will need to learn both technologies to maintain that. Right now what I do is simply refactor things into their own classes where I don't have to think hard on SQL at all as I just move it. My focus is currently on refactoring + feature adding. and I do the refactoring as I go along whenever I come across a section of code I am working on. Having worked with Doctrine a little bit, I came to realize that if I will start using it, majority of my work will become "re-encoding existing SQL into Doctrine", and "learning ways of Doctrine when I come to a particular SQL corner cases and statements that do not easily translate directly to language of Doctrine". And doing so will take up quite a few of my brain power cycles and take away from things like adding features. Doctrine is a paradigm shift from a structural query language to object oriented one. I would love to use it but I am not sure it is the time. Also seeing how my table are mostly joins of multiple tables, using a class-per-table may not suit me that well (at least in terms of workload). I keep myself open to suggestions and strategies. I do want to avoid unreasonable amounts of work if at all possible. Doing nothing is one way as things work now. And that is having SQL everywhere in the code - view, modely, controller, etc. Doing my described strategy approach is basically moving directly-SQL-related code out into separate namespaces while inserting "wiring" to connect it back to the caller functions. (wiring, as in decoupling previously directly connected components and connecting them via functions/class declarations) and that is what I consider to be the minimal amount of work needed to make codebase "better" (more loosely coupled, more maintainable, more flexible perhaps). This is reasonably safe as it leaves SQL as SQL, as in structurally there is no fundamental change. Using Doctrine looks like rehauling a lot of things at their core level and using an approach (class-per-table) that I am not yet sure fits, especially looking at the way I have SQL written (lots of multi-table joins). Plus, learning Doctrine, as I don't have that great of a grasp on it at the moment.
  20. 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 | - ... | - ProductZData Whenever 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.
  21. At University all I cared about is get the project working and heck with security or anything else. And Instructors did not care about security unless it was a security class. Instructors cared about project working and project documentation being in place and a few other esoteric things. Such is reality of University culture. I taught labs and classes at a University for a bit. I pretty much cared only about the concepts I was teaching and not anything else. Security and other pretty may have gotten some folks bonus points, and a notice on my radar for i.e. job recommendations, but not a big effect on the grade, unless I was specifically looking for those.
  22. You can generally skip out on backticks around column names UPDATE int_board_applicant SET Method_Of_Travel='$Method_Of_Travel',... See no quote marks of any kind around Method_Of_Travel? Yep. Save on typing. Those are only required when you are using some reserved words that MySQL would try to interpret.
  23. Is this an acceptable way to instantiate classes? //$_SESSION['product'] = {'ProductA', 'ProductB', ... 'ProductX'} $p = new $_SESSION['product'](); $p->save(); I am usually used to calling out classes explicitly where class name is not a variable but a hardcoded string. Sometimes I use if/then/else in order to do this. Here it is a variable and it bothers me a little bit. But PHP allows me to do this. Is this an acceptable latest & gratest modern PHP object oriented web technology technique or not ?
  24. I don't immediately see how that will work. .. Maybe because of my specific use case, it didn't make sense, or maybe I am not seeing how it could be used. My products are different enough where I think polymorphism will work a little cleaner. With composition, I think I will just have mostly disjoint composites. soo .. say model code ... maybe a couple of the products share the same model code, but the rest are different. How would I code that? What would I call it? If ProductA and ProductB use the same model code, but Product C through F are all different, what would I do?
  25. I am more so asking why use inheritance (in my case). I know I can use it and I have an idea of what I want it to be like, but the "why" part is hazy to me. I don't want to use it just because it's cool to do so, or just because it's "object oriented" if I do, or just because it's the craze right now.
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.