SitePoint Sponsor

User Tag List

Results 1 to 16 of 16
  1. #1
    SitePoint Addict mx2k's Avatar
    Join Date
    Jan 2005
    Posts
    256
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question emulating imports/namespace with constants

    this might help to somewhat emulate a namespace if you desperately need them, however, it currently won't help with using dots for calling methods or even calling a class since you can only call a class using a variable or an identifier.

    using constants, dots, and a folder structure that reflects your namespaces you at least emulate the imports/using or whatever you use to import a namespace. however you still have to call classes individually unless you have multiple classes in a file.

    but it is something that can help let someone know what classes are required and in what file you can find them.

    so if you have an include file that loads your base functions, you would stick this function in there.

    PHP Code:
    define('PtxRoot'str_replace('\\''/'dirname(__FILE__)).'/');

    define('Ptx''Ptx_');

    define('Web''Web_');

    define('UI''UI_');

    define('ErrorHandling''ErrorHandling');


    // example of the class namespace 
    class Ptx_Web_UI_ErrorHandling{
        
        function 
    text() { print '<br /> text';}
    }

    //import namespace function
    function Import $strNamespace 
    {
        (array)     
    $search;
        (array)     
    $replace;
        (string)     
    $fileIncluded '';
        (string)     
    $file '';
        
        
    $search = array( strtolower(Ptx), '_');
        
    $replace = array( PtxRoot'/');
        
        
    // format the namespace into a file path that can be included
        
    $file str_replace($search$replacestrtolower($strNamespace)).'.php';
        
        if (!
    class_exists(strtolower$strNamespace ))) {
            if (
    is_file($file)){
                
    $fileIncluded = include $file;
                
    // return the included class
                
    return $fileIncluded;
                
    // if the file is not valid
            
    }else{
                
    trigger_error('[NAMESPACE ERROR]:  file: '.$file.' was not found, please make sure
                that you the file system and ptx configuration is set up properly'
    E_USER_ERROR);    
            }    
         }    
    }
        

    // thus you can do this at the top of your scripts if you have included this function
    Import Ptx.Web.UI.ErrorHandling );

    # [ folder structure in order for this to work ]  
    // Ptx (your root folder)
    //         Web (inside of root folder)
    //            UI (inside of web folder)
    //                ErrorHandling (class) 
    anyone have any pros and cons of doing something like this or any alternatives methods feel free to drop a reply

  2. #2
    SitePoint Addict mx2k's Avatar
    Join Date
    Jan 2005
    Posts
    256
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    that scary huh?

  3. #3
    SitePoint Enthusiast mjlivelyjr's Avatar
    Join Date
    Dec 2003
    Location
    Post Falls, ID, US
    Posts
    92
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I'll play

    It seems like an okay enough idea. The only thing I don't like about it is how you are using the constants. It makes the Import() look pretty, but it just strikes me as being annoying. Also, the only reason I have ever really wanted to use namespaces is to prevent naming collisions, which this doesn't necessarily solve.

    It is the start of a good idea for managing the file structure and class loading in a larger project. Although I would be inclined to forgo using constansts and just pass a string to Import that could then be parsed. Also might not be a bad idea to extend Import a little bit to also act as a class factory.

    There's my 2 cents....it's probably only worht 1 though.
    Mike Lively
    Digital Sandwich - MMM MMM Good

  4. #4
    SitePoint Guru OfficeOfTheLaw's Avatar
    Join Date
    Apr 2004
    Location
    Quincy
    Posts
    636
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I swear I have seen this on the php.net site in the comments ages ago...

    James Carr, Software Engineer


    assertEquals(newXPJob, you.ask(officeOfTheLaw));

  5. #5
    eschew sesquipedalians silver trophy sweatje's Avatar
    Join Date
    Jun 2003
    Location
    Iowa, USA
    Posts
    3,749
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by OfficeOfTheLaw
    I swear I have seen this on the php.net site in the comments ages ago...
    Looks vaguely reminicent of some of the prado stuff I saw in a recent issue also.
    Jason Sweat ZCE - jsweat_php@yahoo.com
    Book: PHP Patterns
    Good Stuff: SimpleTest PHPUnit FireFox ADOdb YUI
    Detestable (adjective): software that isn't testable.

  6. #6
    SitePoint Enthusiast mjlivelyjr's Avatar
    Join Date
    Dec 2003
    Location
    Post Falls, ID, US
    Posts
    92
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    prado.....I swear I am behind.

    Thankfully I have my trusty Feb. 05 copy of PHP|Arch on my desk.

    Prado kinda does that but takes it one step further. It just has a class factory (pradoGetApplication()) that takes the path to an XML file. The XML file is where the actual name space stuff exists.

    So just consider the aforementioned idea a really light wieght framework very loosely, and somewhat unknowingly based on prado?
    Mike Lively
    Digital Sandwich - MMM MMM Good

  7. #7
    SitePoint Addict mx2k's Avatar
    Join Date
    Jan 2005
    Posts
    256
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    well if you find the comments i'd like to see them to see if they have something better or tighter code. i have php.net manual in a chm, but i haven't come across any namespace stuff yet.

    my goal was to make something someone could easily read that could help with a naming scheme and file structure and not have to repeatedly use or worry about errors in case the class has already been called.
    PHP Code:
    if (! class_exists'myClass' )){
          
    // include class here

    well it might possibly help with keeping the naming without collisions because the class name should reflect the path. only downside is long class names, but an ide with autocomplete would help with that.

    i have done this with constants in order to make it easier to read, plus the idea is to reuse the naming scheme as much as possible. so like Ptx or Core (whatever your root) which comes in handy if you use an ide that autocompletes constants.

    core.web.ui.controls.newssearch should reflect class core_web_ui_controls_newssearch
    core.web.page.newssearch should reflect class core_web_page_newssearch



    but to instantiate a class you would still need to do

    $x = new core_web_ui_test; or

    $class = core.web.ui.test();
    $x = new $class;

    what i have found at php.net is that all classes, even when capitilized, are stored lowercased and you can't use anything but an identifier when naming a class or an indentifier /variable when calling a class. i know some people would hate it, but it would be cool for me to be able to use constants with dot concantination in order to form the name of the class or even something seperate from contstants just used for naming purposes.

    currently i don't see how you could fully be install namespaces into php itself unless the namespaces and their files are held in memory or php was kept in a compiled state, without being depedent on the scripts for each call. but it would be cool to have,

    on the bright side the above would help people to have an idea from where the class is being called from in the folder structure and that the current class/file/code is depedent on those files and where those dependant files are.

    i could make a class factory for it or even extend the idea into a dispatcher, but i would probably need to place an optional array or mixed var in the signature.

    as far as doing what prado does with the xml, i always worry about the overhead in php4 with xml, not to mention the fun of using sax or dom. thats the reason i nixed the idea of using ini and xml files, till i start writing for php 5 (but as i'm writing now, i'm keeping php 5 in mind and make the current scripts both php5 & php4 compatible)

    but after looking at wact and xiarah (spelling?) and other frame works, including dot net (due to job). i've come to some conclusions for guidelines for myself and they are up for debate or critiquing, cause i still have a ton of learning, i've only been doing this (programming) for little over a year.

    1) documentation!
    make the code self documenting. including locations of dependencies (files, objects, etc) . and then create even more documentation, the php doc is great, buut... if there isn't much detail on the flow, variable types, code examples, the main idea, dependcies, default values or the values that are allowed (in cases of a switch statement or other times this is called for) and tons of file paths doing the ../../../../../../home/index.php, that makes it so much harder to read, esp with limited time.

    document know issues and put them all together in a place where people can find them. i spent an hour trying to fix an exception in an application throwing a thread error in vb.net, using the response.redirect, the thing is, it always throws the error when calle, and i mean always. and there is documentation on it, but its soo obscure and oddly placed that it wasn't funny.

    2) keep your code easy to read code even if means long names, even though php is loosely typed, it helps to prefix variables, and use names that would mean the same thing to everyone that would look at it and could read english.


    3) stay away from pear (altogether) & php extensions that are not included with the default download of php when working on something that will be used in many different environments

    4) keep your inheritance from going more than 2 deep

    5) try to write your very base classes to be self containing with 0 or little dependancies.

    when doing research on errorhandling, so many of those classes were tying in email functionality that should have been seperate. If you need to use that class alone, then yeah put in the bare minimum to send an email, otherwise build an email class, the error handler class and seperate master/manager class that would configure the classes and override the errorhandler's built in mail functions, with the email class's full functionality.

    i know alot people don't say reinvent the wheel, but its almost easier to write something from scratch than go through someone elses code, esp if the code has more information about the author and the open source license than through the rest of it.
    Off Topic:


    and i'm sure that someone has already has thought about it or done this, but you can emulate code behinds and all that jazz in php if you really wanted to.
    <? require_once('loadApp.php); inherit('index.class.php'); ?>
    which could read the file that the the tag above is placed in, parse it, remove the php tags and then print it back out to the browser.

    and i'm sure this has probably been done too, but know of anyone who serializes objects or information into the web page? i do know that session does this automatically and puts it into a tmp folder, but i'm just curious about using it to put in the page and wonder if that can be useful.




    sorry didn't mean to write a book. i do appreciate your comments. but due to inflation, high gas prices, i'm sure its worth 25 cents.

  8. #8
    SitePoint Guru BerislavLopac's Avatar
    Join Date
    Sep 2004
    Location
    Zagreb, Croatia
    Posts
    830
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    This namespaces stuff in PHP seems a bit like perpetuum mobile to me. Everyone would like to have it, and everyone has had at least one idea how to make it work, and justr like perpetuum mobile most of these ideas are extremely complicated, but it's still simply not possible: one way or another, there can be no more than one class/function of the same name defined at the same time. Period. At least until a new syntax allowing for it comes about.

  9. #9
    SitePoint Addict timvw's Avatar
    Join Date
    Jan 2005
    Location
    Belgium
    Posts
    354
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    if i'm not mistaken php-dev decided to remove them again... because they were a real performance killer...

  10. #10
    SitePoint Enthusiast mjlivelyjr's Avatar
    Join Date
    Dec 2003
    Location
    Post Falls, ID, US
    Posts
    92
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I am still not sure what I think about namespaces. I know they are great for code organization and preventing namespace collisions, but those are both issues that should be taken care of by being a clean and considerate coder....

    I guess there are always going to be those instances where you are using someone elses code that uses some of the same name classes as yours. I actually ran into that problem myself a few weeks ago when I was integrating RTC into a website. It would DEFINATELY have been handy to have namespaces then. I don't think I'll every really persue that though until php has native support for them (if it ever has native support.) It's too much work for something I personally wouldn't use too often.

    What can I say, I'm a lazy clod.
    Mike Lively
    Digital Sandwich - MMM MMM Good

  11. #11
    eschew sesquipedalians silver trophy sweatje's Avatar
    Join Date
    Jun 2003
    Location
    Iowa, USA
    Posts
    3,749
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Could even happen to concientious coders working in differn libraries for the same company:

    John working on the math lib:
    PHP Code:
    /**
     * helper class for trigonometry
     */
    class Sin {
      
    //...

    Sue working on the theology library:

    PHP Code:
    /**
     * Determine how bad behavior is
     */
    class Sin {
      
    //...

    And last there is poor Mike, who just got a contract with a client to determine how many angles can dance on the head of a pin. He starts his code with:

    PHP Code:
    require_once 'math.inc.php';
    require_once 
    'theology.inc.php'
    and guess what he gets to deal with
    Jason Sweat ZCE - jsweat_php@yahoo.com
    Book: PHP Patterns
    Good Stuff: SimpleTest PHPUnit FireFox ADOdb YUI
    Detestable (adjective): software that isn't testable.

  12. #12
    SitePoint Enthusiast mjlivelyjr's Avatar
    Join Date
    Dec 2003
    Location
    Post Falls, ID, US
    Posts
    92
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yah, I would agree with you there. That's kind of like the situation I ran into a few weeks ago. I should have known better than to try and get away with 'User' for a class name :/. (*shaking head*)

    However, non-native-PHP based namespacing solutions still don't solve that problem without having to go in and renaming a bunch of classes and references to those classes. Which again takes me to the conclusion of: "I'm too lazy"
    Mike Lively
    Digital Sandwich - MMM MMM Good

  13. #13
    SitePoint Addict mx2k's Avatar
    Join Date
    Jan 2005
    Posts
    256
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    This namespaces stuff in PHP seems a bit like perpetuum mobile to me. Everyone would like to have it, and everyone has had at least one idea how to make it work, and justr like perpetuum mobile most of these ideas are extremely complicated, but it's still simply not possible: one way or another, there can be no more than one class/function of the same name defined at the same time. Period. At least until a new syntax allowing for it comes about.
    well i would image that you would have to somewhat keep the scripts in a compiled state or put the namespaces and their class location somewhere in memory, or write to some kind of temp file, flat db file that is php reads from every time it wants to know the location of the class for that namespace, maybe with something built in that wakes up every so often to scan files or something to that effect to really have enable namespaces in php.

    besides the post was about emulating, as in "creating an imitation of" if someone needed it. but all i really did was use a naming convention in conjuction with a folder structure.

    so with a glorified include function that checks to see if that a class already exists in case there are multiple includes for that class, along with checking to make sure that file exists, since you have to include the files anyway, why not make it easier to read, find the file, keep things consistent and type out using an IDE?

    but if you want to get technical, a class identifier in php is essentially its namespace, so if you name classes in relation to your folder structure that should help with collisions and if you have a company or your own library or framework, or even do websites, its a good idea to prefix the class name with one of the above so that you can help avoid collisions.

    yeah its extra work, but better than a little extra work now, than a mountain of issues later

  14. #14
    SitePoint Wizard stereofrog's Avatar
    Join Date
    Apr 2004
    Location
    germany
    Posts
    4,324
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    sweatje

    As long as language doesn't support us, all we can do about it is to invent conventions and follow them. I suggest we fire John and Sue and hire Bob and Alice instead, who name their classes like Math_Sin or Theology_Sin.

    Or, we just read the book your example is borrowed from and switch to that programming language.

  15. #15
    eschew sesquipedalians silver trophy sweatje's Avatar
    Join Date
    Jun 2003
    Location
    Iowa, USA
    Posts
    3,749
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)


    Theology_Sin is just such an ugly name to type in over and over again

    I think I would have to rename the package Moral so I could have MoralSin for a class name and avoid some typing

  16. #16
    SitePoint Addict mx2k's Avatar
    Join Date
    Jan 2005
    Posts
    256
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    $bob = new bob();

    $bob -> createNewAction( new MoralSin('DOS ATTACK') );

    $bob -> createNewAction( new MoralSin('uses MS technology'));

    $bob -> createNewAction( new MoralSin('watches deseperate house wives'));


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •