Jump to content

BrandonK

Members
  • Posts

    27
  • Joined

  • Last visited

Posts posted by BrandonK

  1. using a for loop with count is inefficient.  At the beginning of each loop, the script has to recount the array, so if your query ever returns a large amount of data (say 100 rows or so), you might notice some lag.  I prefer using foreach loop:

    foreach($result as $row)
    {
       echo $row['username'];
       echo $row['password'];
    }

     

    Same results and it should be faster.

  2. They shouldn't be.  You'd have to post your code, but numerics should stay:

    <?php
    $str = 'Shrek2 vs Shrek 2';
    $str = str_replace('&', 'and', $str);
    $str = preg_replace(array('/[^\w\s-_\\/]+/', '/[^\w]+/'), array('', '-'), $str);
    echo $str;

  3. I threw Cheech-Chong in there to show that it preserves existing hyphens.  You initial example still works with Cheech & Chong.  I tend to make urls lowercase because servers can be case sensitive.  I do think that search engines are smart enough to not mistake Cheech with cheech, but its always better to error on the side of caution.  strtolower() is easy to add.

  4. I discovered a bug with the regex that I posted.  Since I am planning on using this function to replace my current method for creating slugs, I ran it through some of my odd product names...

     

    If your product name has a hyphen, it is stripped by the \p{P} so:

    "Cheech-Chong Up In Smoke" becomes "CheechChong-Up-In-Smoke"

     

    After a lot of trial and error, I came up with this:

     

    <?php
    $str = 'Cheech &     Chong\'s    Nice     Dreams';
    $str = str_replace('&', 'and', $str);
    $str = preg_replace(array('/[^\w\s-_\\/]+/', '/[^\w]+/'), array('', '-'), $str);
    echo $str;

     

    It loses some of its simplicity that we had earlier, but it allows the above string to come out as "Cheech-Chong-Up-In-Smoke" as well as handling backslashes like I needed it to.  If someone else has an idea to clean it up, I'd be happy to run it through my tests.

     

    P.S. For those that are interested, here's what I found out about the \p variations:

    not matched by \p{P}: `~$^+=<>
    {Pc}:	_
    {Pd}:	-
    {Pe}:	)]}
    {Pf}: ????? - no clue, probably has to do with the placement of the punctuation
    {Pi}: ????? - no clue, probably has to do with the placement of the punctuation
    {Po}:	!@#%&*:"?\;',./
    {Ps}:	({[

    Not much more info here: http://www.php.net/manual/en/reference.pcre.pattern.syntax.php

  5. Very nice idea tgavin.  That's a lot more efficient than what I was using before.  I added one more step to the replacement for slightly better results (strips punctuation):

    <?php
    $str = 'Cheech &     Chong\'s    Nice     Dreams';
    $str = str_replace('&', 'and', $str);
    $str = preg_replace(array('/[\p{P}]+/', '/[^\w]+/'), array('', '-'), $str);
    echo $str;

     

    This way you don't get Cheech-and-Chong-s-Nice-Dreams, but instead Cheech-and-Chongs-Nice-Dreams. YMMV.

     

    \p{P} matches all punctuation (PHP 4.4.0+ and 5.1.0+)

  6. I plan on using the Zend_Framework in my next big project, and I am starting to play around with it.  I am currently debating Zend_Db vs the standard PDO and I think that the ZF version is a lot nicer.  I plan to extend the class just a little and wrap it in my own namespace.  I have created the connection like this:

    <?php
    try {
    
    	$db_config = array(
    		'host'     => $hostname,
    		'username' => $username,
    		'password' => $password,
    		'dbname'   => $dbname,
    		'profiler' => true,
    		'adapterNamespace' => 'My_Db_Adapter'
    	);	//in the future I may use load from Zend_Config or something
    	$db = Zend_Db::factory('Pdo_Mysql', $db_config);
    } catch (Exception $e) {
    	throw $e;
    }

    This works fine, and I think its fairly straight forward.  One problem I have is related to the exceptions, but that's a different post I guess.

     

    Then I want to come down and make some queries:

    <?php
    $sql =	"
    SELECT name
         , alpha
      FROM countries
    WHERE id < :max_id
       AND alpha LIKE :alpha";
    
    $stmt = $db->prepare($sql);
    
    $stmt->bindValue(':max_id', 5, PDO::PARAM_INT);
    $stmt->bindValue(':alpha', 'A%');
    $stmt->execute();

    But this is where I get mixed up as to what I should be doing.  Zend_Db::execute() will return false when the query has an error (right?), but it will also throw an exception.  Exceptions override a return, so I have to put a try {} catch() {} around every query I make??  Without implementing a Table Data Gateway or other data access pattern, is there a "better" way to use this class?

  7. 1) Wordwrap() does not truncate the string, it merely makes it wrap after X characters.  If you want to truncate the description, use substr()

    2) You will get a product description for each product since you are looping through all of your products

    3) Removing old/unused code, irrelevant code and intending your code can make understanding your code a lot easier for those trying to help you.

  8. I always hate people who ignore the OP's question and offer a different solution, but I have to be "that guy".  Instead of adding of this complexity with changing global variables for the sake of case-insensitivity, why not just use the appropriate error handler to do this for you?  On your 404 page, you can try and see if the the lowercase version of the page exists.  If it does, use a 301 redirect to send the user to that page.  This has an added SEO benefit, and it separates the logic.

     

    If I'm missing the reasoning for this plugin, just ignore me.

  9. The way I usually handle forms, is to have them submit to themselves.  Include all of the processing and validation of your form above the form only if the form has been submitted.  If there are any errors, show the form again and list the errors.  If there were no errors, hide the form, send the e-mail and display a confirmation message.

  10. Why can't your artist class create its own instance of the db?  Use a singleton pattern if you are afraid of multiple connections, but why should one class have to share with another?  What if your artist_control class changes completely to a different database type?

     

    My thought would be to create layers, and don't make them dependent on each other.

  11. The public properties were simply there for examples.  I rarely declare object properties and public because I like to make my objects closed so that I can control access using various forms of getters.  Its easy to say that all access to variables must use a getter/setter, but I was more curious if its possible to enforce that rule.

     

    I am not trying to make PHP a strong typed language.  I am simply trying to add extra security to my program.  For example, certain variables cannot be changed once they are initiated.  One of my objects is a product class.  If I change the id of the product in the middle of processing the object, I may start getting information from two separate products at once... While its easy to say "well don't change that id ever", but accidents do happen (especially when new programmers join a project).

  12. I know that it is possible to define a __set() method inside a class so that any variable declarations must go through that function.  Inside of that __set() method I am able to impose a specification class for certain variables that I need to.  This all works great... My question is, can I do this inside the class scope also?  I want to make sure that it is impossible for me (or any other programmer that may join the project) to set an illegal value for certain variables.  Some are as simple as requiring numeric or certain datatypes, while some must match specific regular expressions.

     

    To show some code, here's what I'm asking about:

    <?php
    
    
    class StrictTest {
    public $pub_id;
    protected $pro_id;
    
    public function __set($property, $value) {
    	$method = 'set'.ucwords($property);
    	if (method_exists(__CLASS__, $method)) return $this->$method($value);
    	else $this->$property = $value;
    
    	return true;
    }
    
    public function setPub_id($value) {
    	if (is_numeric($value) && (int)$value > 0) {
    		$this->pub_id = (int)$value;
    
    		return true;
    	}
    
    	return false;
    }
    private function setPro_id($value) {
    	if (is_numeric($value) && (int)$value > 0) {
    		$this->pro_id = (int)$value;
    
    		return true;
    	}
    
    	return false;
    }
    
    public function testPro($value) {
    	return $this->pro_id = $value;
    }
    }
    
    $t = new StrictTest;
    $t->pro_id = 'String';
    $t->pub_id = 'String';
    
    var_dump($t);
    
    $t->testPro('String');
    
    var_dump($t);
    
    ?>

     

    When the protected property pro_id is called from outside of the class scope, the setter is used correctly.  However, since pub_id is public, there is direct access to the variable and that bypasses the setting.  Inside of the class scope, direct access is granted to the protected property, and again the setter is bypassed.  Anyway to solve this?

  13. Very simple:

    	$promo_content = file_get_contents("http://www.MYDOMAIN.com/scripts/check_order_promo.php?order=".$ordernum);
    if ($promo_content == 1) {
    //this order wants a promotional item
    }

     

    MYDOMAIN.com is not the only domain that is experiencing the lag.  Also, as stated above, the lag is not in the response, but actually when the page finishes rendering.

  14. I am having an issue with a local intranet script that has been running problem free for many months now.  Earlier this week I upgraded the PHP version on the sever as a requirement for a separate script that was upgraded on the server.  When I did this, I did not change the php.ini configuration, or ANY code on this script.  Now when I run this script it hangs.

     

    I have narrowed down the script to a single line of code, and a even a single function: file_get_contents()

     

    The return from the function is quick.  I can see the return echo'ed out and the script continues processing after that.  What does not happen is the page becoming "ready".  The page is in a "loading" stage for 3+ seconds longer than it needs to be.  My thought is that the problem lies in closing the connection with the file, but I cannot verify that.  I have tried using the fopen()/fread()/fclose(), stream_get_contents() and even some quick and dirty curl, but those all suffer from the same lag.

     

    Here are come quick before and after benchmarks:

    PHP 5.1.2 - 0.652, 0.813, 0.703

    PHP 5.2.4 - 5.672, 5.547, 5.563

     

    I am able to downgrade the PHP installation and the performance issues goes away.  I have tried upgrading to to 5.2.5 and even using the recommended php.ini for that setup, but the problem does not go away.

     

    I have asked this question on another forum, but I was unable to get any solutions: http://www.sitepoint.com/forums/showthread.php?t=528407

     

    Can any of the PHP gurus think of a cause of this problem?  Or maybe even a temporary work around?

  15. Using the payam calls methods statically.

    Which I don't think will work in this case.

     

    I have my "URI parsing" class written already.  This will be the core function for my shopping pages (it decides the criteria and sorting for the products that will be displayed), so it should be processed on every page first.  From there my other functions, "breadcrumb" and "display results" will need to call the parsed variables.  What is the best way for me to do this?

     

    $parseClass = new parseme();
    $parsedArray = $parseClass->getParseData();
    
    $breadcrumbClass = new breadcrumb($parsedArray);
    $breadcrumbHTML = $breadcrumbClass->getBreadcrumbHTML();

     

    or is there a better method? (I hope there is)

     

    Thanks guys, you've been helpful.

  16. Thanks for the link, Boo.

     

    The question I was trying to ask (I think I beat around the bush too much with it though) is how should all of these different features interact?

     

    I have a couple core functions:

    - URI parsing - validating user variables, etc.

    - Breadcrumb - all pages use a breadcrumb based on the array that was validated from 'URI parsing'.

    - Filter menu - Look at the filters that were validated in 'URI parsing' and offer ways to narrow down the results further, or remove filters if there are some currently active.

    - Display results - Using the filters that were validated in 'URI parsing', query the database and show the products that match every requirement.

     

    In a perfect world, 'URI parsing' runs exactly once and each of the other functions can feed from that data.  The only thing that may be odd is that 'URI parsing' and 'Breadcrumb' is needed on a couple pages where 'Filter menu' and 'Display results' are not.  Because of that, I need to figure out how to design those two functions to be re-usable.

     

    Knowing all of those details, should I be trying to write this as a single class with limited public functions to be called from the pages that need this information?  Or should I write this so that certain functions are in their own classes and each class interacts with another?  What worries me about that approach is how to I require steps to be taken (eg. 'URI parsing' has to be called first)?  I honestly don't see these functions being separate classes, they seem too dependent for that to work well.

     

    I appreciate any input, thanks.

  17. I'm doing a complete rewrite of a rather messy product page I wrote a few months back.  Since then I've done 2 other programs in my version of OOP.  I know that if anyone else looked at the code they would be confused at parts and laugh at parts.  I've read a couple books and I have a much better understanding of PHP's OOP (which is pretty different from the Java I originally learned on).  I've already looked at the features of the page and what I want it to do, etc., but I can't decide on how the framework should be done.

     

    There are a couple functions that I think will make up the entire page.

    Variable validation/URI parsing - pulls the variables out of the URI, validates and says these are the requirements for all products shown on this page.

    Breadcrumb - Create a simple breadcrumb for each variable that we parsed.

    Filtering menu - Using the variables parsed, give the user options for narrowing down the results even further.

    Display results - Thumbnails of each product, etc.

     

    There are some more functions obviously, but that should be enough for my question.  How would you set this up?  Is it possible or even logical to have the validation/parsing class create global variables?  Or would I be better off calling something like $parsing->getFilters() every time I needed access to them?

     

    I'm still very new to the OOP designing.  I'm reading books, but it seems like there are always a couple unanswered questions once I put down the books and try to "fly solo".  Thanks in advance.

×
×
  • 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.