1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

A PDO class to make it easy on newbies and lazy coders

Discussion in 'PHP' started by eritrea1, Oct 8, 2013.

  1. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #41
    You are encountering exactly what I was talking about with exception handling. Try/catch cannot catch operations in a child routine unless you trap it by using your own exception handler (messy), or handle it internal to the function calling the one throwing the exception in the first place.

    Getting around that would involve adding try/catch inside your method, and figuring some way to return values -- most likely using throw:

    http://php.net/manual/de/internals2.opcodes.throw.php

    Though again, at that point you're getting SO complicated and adding so much overhead you might as well just use PDO directly instead of wrapping it. REALLY if you 'need' a routine to automatically select between query and prepare like that, you probably have no business using PDO in the first place.

    That's the problem with a lot of frameworks, no matter how simple they seem or how much they make it 'easier' -- they often create more problems than they solve. It's the "throwing more code at it" trap. No matter how much you might think the more code makes it 'easier', in the long term it prevents people from learning what they NEED to learn to be qualified to make rational choices about their code.

    ... and trust me, it took a good number of years for me to learn that lesson the hard way; admittedly that experience may have swung my pendulum a bit too far the other direction -- to the point people say "framework" and it raises the hackles on my hackles -- but as I'm sure you're starting to discover with this, there's a reason for it.

    Little tip though -- your logic flow is unneccesary. First up, I would avoid the : / : else: / endif structure and just use curly brackets. It's cleaner, clearer and easier to follow. Those only seem to exist for the scriptttards who do <?php ?> on every blasted line resulting in impossible to follow code... likewise if your primary IF result does a return, you don't need to else as the return is run right then and there.

    So something more like:
    public function doSimple($query, $value = null) {
    	try {
    		if (empty($value)) return parent::query($query);
    		$stmt = parent::prepare($query);
    		$stmt->execute($value);
    	} catch (PDOException $e) {
    		return $e;
    	}
    }
    Code (markup):
    You could then check the type of doSimple for error trapping... again though, notice it doesn't need a 'else' condition because a return is, well... a return. Nothing past that point will be run.

    ALSO THOUGH, beware that mysql errors in PDO do NOT throw an exception!(which means try/catch does NOT work on them!) You must manually trap ::errorCode() or ::errorInfo() -- and that's something that if your function provided in a more meaningful manner would go a long ways towards helping beginners with.

    In fact, if instead of trying quite so hard to simplify how PDO works (which is pretty damned simple to begin with) and instead focused on making the error handling more robust but easier to maintain, then you'd really be onto something. Having to trap both PDOExceptions AND PDO::errorInfo() is a pain in the ass -- making that into a consistent single handling mechanism could really make life easier for those just starting out.

    Of course, learning PHP error handling and PDO error handling can be a pretty steep curve.
     
    deathshadow, Oct 29, 2013 IP
  2. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #42
    Which BTW, is why you are seeing more and more people who use PDO setting:
    $pdo->setAttribute(PDO::ERRMODE_SILENT);

    so no PDO operations actually THROW (so no more try/catch) and instead manually catch PDO::errorCode() after every operation. Since TRY/CATCH already doesn't grab SQL errors, you might as well say screw it and use the error trapping technique that does.

    So if you were to set that attribute in the overloaded constructor, you'd then do this:
    public function doSimple($query, $value = null) {
    	if (empty($value)) {
    		$statement = parent::query($query);
    		if ($this->errorCode() > 0) return $this->errorInfo();
    	} else {
    		$statement = parent::prepare($query);
    		if ($this->errorCode() > 0) return $this->errorInfo();
    		$statement->execute($value);
    		if ($this->errorCode() > 0) return $this->errorInfo();
    	}
    	return $statement;
    }
    Code (markup):
    (times like that I REALLY wish PHP had macro's)

    then when you call doSimple...

    if (get_class($statement = $conn->doSimple($query)) == 'PDOException') {
    	die('The following PDO error occurred: ' . $statement[2]);
    } else {
    	// $statement must be PDOStatement, so process the result
    }
    Code (markup):
    But again, that's getting so complex you might as well handle it normally.
     
    deathshadow, Oct 29, 2013 IP
    eritrea1 likes this.
  3. eritrea1

    eritrea1 Active Member

    Messages:
    182
    Likes Received:
    9
    Best Answers:
    2
    Trophy Points:
    70
    #43




    Man.. this really sucks. I had hoped that the class would provide to be useful somehow, and didn't even think for a moment, that it wouldn't be any better than using plain PDO no matter how I do it. I don't get it, there is even popular Pdo wrapper here http://www.imavex.com/php-pdo-wrapper-class/ , which is more complex than what I tried to do, in other words... according to your opinion, they must be doing it wrong too, or adding unnecessary complexity. I just understand, you may not think that making a PDO wrapper may not help boost performance, but you are completely playing down the idea, that any PDO wrapper likely to be made, or have been made is useless, in every sense...

    Anyway, I understood some things, and have learned it is not as simple as I had once thought it would be. And, I only happen to know about PDOException, while talking about exceptions, so It'll be hard to fiddle with the exception class.


    ehh.. I am not sure what to do... But, I am certain that there must be a way in which I can minimize the lines of codes it takes to write a query, while not affecting the performance or slowing down the speed at the same time. So, I'll just try to twig it a bit and leave it at that, and find another exciting project, because this if too hard.

    thanks for the help.
     
    eritrea1, Oct 29, 2013 IP
  4. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #44
    That 'wrapper' is exactly what I'm talking about... the constructor is near identical, so it doesn't enhance things in a really useful manner. You move on to 'delete' or 'insert' -- well, let's use their examples:

    $db->delete("mytable", "Age < 30");
    Code (markup):
    How is that ANY simpler than...

    $db->exec('DELETE FROM mytable WHERE Age < 30');
    Code (markup):
    or their:
    $lname = "Doe";
    $bind = array(
        ":lname" => $lname
    )
    $db->delete("mytable", "LName = :lname", $bind);
    Code (markup):
    compared to:
    $statement = $db->prepare('DELETE FROM myTable WHERE LName = :lname');
    $statement->execute(['lname' => $lname]);
    Code (markup):
    or take this insert:
    $insert = array(
        "FName" => "John",
        "LName" => "Doe",
        "Age" => 26,
        "Gender" => "male"
    );
    $db->insert("mytable", $insert);
    Code (markup):
    as opposed to not using the library:
    
    $statement = $db->prepare('
    	INSERT INTO myTable (
    		FName, LName, Age, Gender
    	) values (
    		?, ?, ?, ?
    	)
    ');
    $statement->execute(['John','Doe',26,'male']);
    Code (markup):
    I'm just not seeing enough difference to be dicking around with the overhead of a library in ANY of those cases! The only thing it seems to be there for is to prevent people from learning the underlying SQL syntax... and that's not a good thing. If I WERE to automate any of those, I'd be doing so by way of using named queries -- which also nets you a better security method since your code would never actually pass a query to the extended PDO object.

    In many ways, I start to wonder if these sorts of 'libraries' are in fact some manner of intentional sabotage to keep people ignorant... though I don't see that anywhere near as much on the PHP side as I do from say, the cult status jQuery has accomplished.

    There's this noodle-doodle idea circulating right now that more code makes things faster or easier -- see the idiotic train wreck of crap known as jQuery where 90% of what people do with it is either CSS' job, has no malfing business on a website in the first place, or could be done far simpler and in less code WITHOUT relying on the library (NOT even counting the library against the total)... or AJAX loading content because of 'pageloads are evil' without caring if it pisses all over accessibility and search, or any of the dozens if not hundreds of other sick trends of the past five to six years which amount more to bandwagon, transfer, glittering generalities, card stacking and testimonial than reality. (probably why I counter with name calling and plain folks -- they already used up the other five core propaganda techniques.)

    For the most part people run their mouths about this type of stuff being simpler when they are in fact more complex, easier when they are for the most part no more so than just using the damned native code, or more efficient when they just add more overhead. REALLY makes me wonder just what the blue devil is in the kool-aid. there's something in the water...

    I dunno, maybe I just have different meanings for the words easy, simple and efficient. Every time someone uses those phrases in reference to the vast majority of 'frameworks' be they PHP, HTML, CSS or javaScript, I can't help but knee-jerk into a Montoya-ism...

    Of course, I've never fallen for the biggest lie of all. As a man much wiser than myself once wrote:

    "You can torture me, with Donnie and Marie. You can play some Barry Manilow. ... or you can play some schlock, like New Kids On The Block, or any Village People song you know. ...or play Vanilla Ice hey, you can play him twice, and you can play the Bee Gees any day. But Mr. DJ, please I'm beggin' on my knees, I just can't take no more of Billy Ray".

    Just because something is popular doesn't mean it's any good. The Fox Says Oppa Gangnam Style Hey Macarena...
     
    deathshadow, Oct 29, 2013 IP
  5. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #45
    Quoting Weird Al? Almost makes you human, you know ;)
    I, however, tend to agree with you, mostly, albeit maybe not for the reasons you would consider acceptable. Frameworks for HTML and PHP I don't see much use for. jQuery and SASS am I however a big fan of, since they both makes my life easier. Maybe not pageload-time, and maybe, just maybe, it'd be simpler to write all the js-functionality in plain js, but that would mean I would have to dwelve into a language which I'm not a fan of at all (javascript) - jQuery uses a (maybe twisted) syntax that makes sense in my world :)

    And yes, frankly, most of what is being done with jQuery, Mootools and all the other js-frameworks, is of course possible to accomplish using regular js - however, much of the work being done is so complex, it helps having simple "helper-functions" making it slightly faster to write the code for certain effects and events. As for usability - people don't really care that much - they want flashy, smooth, animated, and preferably something that doesn't seemingly reload any pages. Is this a new Geocities/Myspace-fad? Maybe. However, I do prefer this to the blinking fonts and rotating gifs from the past.

    As for SASS, I think that is a blessing. It makes writing CSS quicker and easier, and providing you with stacking, variables etc. which doesn't really affect the final product, since it parses the written .scss-file into normal .css before publishing.
     
    PoPSiCLe, Oct 29, 2013 IP
  6. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #46
    That could be an experience difference -- for me all these 'new fangled' languages are just C in drag. JS, Java, PHP -- they're all C syntax C family offshoots and to be frank, the only real differences are so minor as to make no never-mind. (and even if you put a dress on a pig...) Since I learned how to write Pascal and C in the '80's, these 'newer' languages click for me almost instantly. (as opposed to say Ruby or Python, which I still can't see any real world reason for ANYONE to want to use!)

    Whereas:
    For me jQuery often seems needlessly cryptic, and usually doesn't make any sense to me -- though more often than not the biggest problem is it prevents developers from learning the advantages of using variables or references, and when not to use them. In general it prevents people from learning the underlying language or how to use it, and as such few if any using it are qualified to offer an opinion on if it's actually any better or not... they just parrot what everyone else using it claims without taking the time or effort to rub a few brain cells together. Propaganda, feel the power.

    I can agree with that, but that's no reason to be using scripting to do CSS' job, use ten times as much code as necessary, and abandon accessibility, graceful degradation, etc, etc... Honestly, to me about 90% of what jQuery does belongs on the cutting room floor, or should be built into JS already. (and with ECMA 262-5 now is).

    I mean... getting elements via CSS style selectors? I can get behind that. Creating a new element via selectors? Cool too. Class handling functions? Sounds good. (thankfully ECMAScript 262-5 introduced .classList)

    But most of the rest of it? pointless bloat or crap that has no business on websites in the first damned place.

    ... and those who forget the past. :D

    It's like people have forgotten all the things we spent the past fifteen years trying to undo... like stupid flash animations, like accessibility failings. It's throwing all the improvements of 4 Strict and the WCAG in the trash because dumbasses are wow'ed by flashy nonsense, who cares if it's actually useful to end users or who it alienates. That's how the PSD jockeys have taken over the industry with their completely useless bullshit layouts, and now the script-tards have joined the party.

    In which case just write the damned CSS flat in the first place. If you end up with enough CSS to 'need' anything SASS or LESS or any of the rest of that garbage does, there is probably something horrifically and terrifyingly wrong with your CSS! (and quite likely the markup as well) Like failing to grasp the point of inheritance... or how to leverage semantics ...or how to condense properties ...or even the existing mechanism for sharing values between elements. Even more likely is another 'trap' and 'flawed thinking' that are the cornerstone of such systems. SASS and LESS tread into the same trap as CSS frameworks, in that they actively encourage the use of presentational classes, which is JUST as bad as the presentational markup we've been told for FIFTEEN YEARS TO STOP USING! You might as well start saying class="red" or class="leftColumn" or other such idiocy -- which is the EXACT same thing as using FONT or CENTER or ASIDE.

    Which is why I laugh when people cry "ASIDE isn't the same thing as CENTER" -- yes, yes it is...
     
    Last edited: Oct 29, 2013
    deathshadow, Oct 29, 2013 IP
  7. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #47
    Well... personally speaking, I think SASS is a good thing, if used properly - it makes tedious work less tedious, since you have threadable classes and can easily create sub-elements of one master-ID - which I personally like a lot. As for the usage of variables in CSS, I think they're a good thing - personally, I mostly use them to define a color or border-settings one place, and then just use the variable whereever it's needed. Is it possible to do the same in pure CSS? Of course. But it saves me a few minutes, and makes replacing stuff simple by chaining one variable instead of replacing all (by search and replace) or doing a manual search if you want to change most but not all.

    It's just a way to work, simple as that. As a SASS-file is simply a CSS file when uploaded to the server also helps in avoiding the bloat or things you'd need a running parser to use - it's simply just easing of the plain work.

    As for avoiding presentational CSS, I'm all for it, but I do admit that I do like to just have a class for "float: left;" for instance, and the like. Makes it easier to just add a class to an element, instead of having to have separate CSS-rules for each element needing a float-attribute :)
     
    PoPSiCLe, Oct 29, 2013 IP
  8. eritrea1

    eritrea1 Active Member

    Messages:
    182
    Likes Received:
    9
    Best Answers:
    2
    Trophy Points:
    70
    #48
    Ok, enough with hijacking this thread. :)

    The real problem was about this damn PDO class, which still is annoying me. I honestly wrote it the first time, because I had a big personal project I had to work on, and it required me to have countless simple CRUD statements inside the application, thus ... I needed to abstract/wrap the PDO class just to simplify the whole messy code I was writing for debugging, code clarity, or performance improvements. Then, I could not control myself, thinking I had created something useful, and decided to upload it on github. Now, after-all this... I am putting my project to a halt, because I can't move on any further, without the right approach. I've to find ways to get rid of writing like this for each query.
    try{
            $stmt = $conn->prepare('SELECT * FROM users WHERE name = ?');
            $stmt->execute(array($_POST['Simon']));
        }catch(PDOException $e){
            return $e->getMessage();
        }
    
        if($stmt->rowCount()){
            return  $stmt->fetchAll(PDO::FETCH_ASSOC);
        }else{
            return 'Query failed';
        }
    Code (markup):
    the above is the example from the github page, but I literally have many queries like that in my class, and the project has a heavy use of database query so, it is a complete mess now.



    Is, there any alternative to this at all?
     
    eritrea1, Oct 29, 2013 IP
  9. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #49
    In my experience if you need to do those things, you're doing something wrong... or have bloated CSS. It's VERY easy to look at the SASS code, think you have something lean/clean/efficient -- but a good hard look at what it outputs and then has the cojónes to call it CSS, and very quickly you'll start to ponder...

    I can understand the allure -- I was there once. But it defeats one of the entire reasons to use CSS ... the same problem using STYLE as an attribute or using "ALL" as a media type... It makes it very hard or outright nonsensical when you go to target different media targets, or now with responsive layout media selectors. It makes it hard and outright confusing when/if you want to do things like reskin, run multiple skins at the same time off one codebase, etc, etc... that's why we have CSS and why separation of presentation from content exists.

    Instead of using a class to say it has a certain presentation, you should be asking WHY is it getting this presentation, what makes it so special, what is it? Classes and ID's should then reflect that -- since any static description of what something looks like has no business in the HTML. (It's bad enough using <small> for de-emphasis, <b> for proper titles and <i> for literary titles since that's what they would be in professional writing -- the core of proper semantics.)

    Failing to keep that presentation out of the markup gets really confusing when a class like "floatLeft" isn't floated on a narrow display, or "redText" is blue in a different skin and black/bold for print, or something you say is "centered" isn't at different screen widths. It's actually why I stopped using div#sidebar and just call it #extras -- since now that I'm using responsive layouts it isn't a sidebar when it's a single column layout.

    SASS has a lot of things that further add to the confusion -- like nested rules. It's confusing enough a mess doing so with media selectors without the absolute nightmare that it turns inheritance and specificity into -- well, unless of course you use five times as many classes as you need. Parent selectors just make code harder to read in the same way just blindly dumping CSS property/value pairs onto single lines... and all these are for what exactly? Not typing an extra maybe quarter-k over a typical 16k of CSS? Seems sketchy to me.

    Though in case you couldn't guess, I have no use for the TLDR re-re's... So oh noes extra typing?

    Worse, it seems like most people using SASS intentionally avoid using condensed properties, particularly on things like FONT. Hell, if memory serves even their own example code pulls that idiotic stunt. Was one of the first warning flags that made me reject it as crap... Well, on top of the time wasting extra step of having it be turned into actual CSS.
     
    deathshadow, Oct 29, 2013 IP
    ryan_uk likes this.
  10. ezprint2008

    ezprint2008 Well-Known Member

    Messages:
    611
    Likes Received:
    15
    Best Answers:
    2
    Trophy Points:
    140
    Digital Goods:
    1
    #50
    long hand code and labeling is still best. Work on 100 sites over a time period ..then come back and look at your short hand lazy code and stare at it ..trying to put yourself back in the moment of what the heck you were thinking as far as function and flow of the site. (that's where your time saving becomes lost)
     
    ezprint2008, Oct 30, 2013 IP
  11. eritrea1

    eritrea1 Active Member

    Messages:
    182
    Likes Received:
    9
    Best Answers:
    2
    Trophy Points:
    70
    #51
    I'm trying to understand what you just wrote. Can you elaborate a little bit.
     
    eritrea1, Oct 30, 2013 IP
  12. ezprint2008

    ezprint2008 Well-Known Member

    Messages:
    611
    Likes Received:
    15
    Best Answers:
    2
    Trophy Points:
    140
    Digital Goods:
    1
    #52
    always label your code

    // This function is for ....
    $etc

    // this code is for doing this....
    $code here

    when you go back 1 year or 5 years later to a site and its filled with shorthand and repetition functions throughout site you will waste time trying to fully REMEMBER what its ALL for ..BUT if its labeled you can see what its for. Labeling code is so you know what it is, and any NOTES to self about if/where its also part of functions/flow throughout the site.
    That way you can read and see your notes.

    // The next code block is also used in similar way on (such and such page) but is doing this or that instead.

    label /note your code as if you were explaining it to somebody else looking at it for the first time..because in a year or so that person might be you. lol
     
    ezprint2008, Oct 30, 2013 IP
    eritrea1 likes this.
  13. eritrea1

    eritrea1 Active Member

    Messages:
    182
    Likes Received:
    9
    Best Answers:
    2
    Trophy Points:
    70
    #53
    Got it.
    I will finally put something up together, and just be done with the class.
    Thanks.
     
    eritrea1, Nov 4, 2013 IP
  14. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #54
    You mean comment -- and that's why you lost just about everyone who thought you meant the TAG "label" or something else.

    Though on that subject, AVOID unnecessary comments, particularly in an interpreted language. Your examples:

    Quite often when people do that, they do so unnecessarily, or because their variable or function names are gibberish.

    You see that on the HTML side all the time with idiotic BS like:

    <!-- start content -->
    <div id="ctwp1">

    Of course it's the start, that's what opening a tag means... .and if you bother using a legible name, the comment ceases to serve a legitimate purpose... so just say:

    <div id="content">

    or the flip side:
    </div>
    <!-- end content -->

    While it might be useful to know what DIV you are closing, putting it after could land it between siblings resulting in rendering bugs in IE and FF, and of course it's the end, that's what the / in </div> means... That's why I write:

    <!-- #content --></div>

    Putting the comment before the close prevents those bugs (since it can therein never be between sibling elements), adding a # makes it clear we're closing an ID, and naturally </div> means it's the end of something.

    You see the same thing in many people's PHP:


    /*************************************
    * strip comments off string *
    * parameters $s = string *
    *************************************/
    function scos($s) {

    The massive asterisks for nothing crap not only makes the parser take longer should your code not be cached, if you need comments like that you probably have no business looking at the code in the first damned place! If you bother to use meaningful names on things:

    function stripComments($string) {

    What the devil do you even need comments for?

    There's a VERY good article on IBM's linux developer site about commenting practices. It's meant for C programmers, but I believe programmers of any language can benefit from it. I'm particularly fond of the "Oh, NOW we're done?" part.
    http://www.ibm.com/developerworks/library/l-clear-code/

    Don't just comment because you can, comment because you need to. Verbose code is ALWAYS better than comments every other line, particularly in anything that is runtime parsed or interpreted... a lesson from the '80s many seem to have never learned in this day and age.

    Sometimes the way people slap comments into their code, I wonder if they're being paid by the K-Loc '70's style.
     
    deathshadow, Nov 4, 2013 IP
  15. eritrea1

    eritrea1 Active Member

    Messages:
    182
    Likes Received:
    9
    Best Answers:
    2
    Trophy Points:
    70
    #55
    https://github.com/simon-eQ/PdoWrapper

    As you can see, I finally applied your advice, and it works like a charm. Thanks, I've never used references before, so their power was all but known to me.
    Now, everything is smooth, except catching that error code from the parent::query().

    thanks for everything
     
    eritrea1, Nov 13, 2013 IP
  16. ezprint2008

    ezprint2008 Well-Known Member

    Messages:
    611
    Likes Received:
    15
    Best Answers:
    2
    Trophy Points:
    140
    Digital Goods:
    1
    #56
    Labeling the variables so that they make sense and maybe having a separate file with flow chart and variables names helps
    and then a comment/label on the code themselves
    // This is ..
     
    ezprint2008, Nov 16, 2013 IP