SitePoint Sponsor

User Tag List

Page 6 of 16 FirstFirst ... 2345678910 ... LastLast
Results 126 to 150 of 384
  1. #126
    SitePoint Guru
    Join Date
    May 2005
    Location
    Finland
    Posts
    608
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by kyberfabrikken
    While I can't really conjure up rational arguments, I'm still not keen on changing the signature of IHandler->execute(). Regarding you latest post, I think the LogManager may be overkill. Why would we need multiple logs ?
    Me neither, which is why I thought Request/Response contexts would make sense. LogManager is there because I thought having a situation where you'll need to pass messages of two distinct types isn't too far fetched.
    If we are going to pass all sort of stuff (such as $_FILES, $_SERVER and LogManager) around, I'd prefer a single ServiceLocator (Context) rather than split it into two. For example, the Loggers are output to some scripts, but input to others, which makes them odd to put in the right spot.
    After a few days, I'm agreeing with you. As for my own version, I'm converting to a single Context after all.
    Maybe we could give it a rest and bring it back up in a while?

    I'd be much more interested in peeking into a form-factory class as the one tharos was calling for. For a start, I suppose that we could just extend the FormController class ?
    Certainly. We should be moving on already. Did this episode drain all our participants?

  2. #127
    SitePoint Wizard silver trophy kyberfabrikken's Avatar
    Join Date
    Jun 2004
    Location
    Copenhagen, Denmark
    Posts
    6,157
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Ezku
    We should be moving on already. Did this episode drain all our participants?
    Well. To speak for myself, I have had the feeling for the last posts, that the discussion was more and more turning into a monologue. (Although a polyphonic one).

    Arborint, who have been a driving force in the thread, obviously disapproves on the current design of the ApplicationController, which on the other hand, Ezku and I have been quite happy about. Since Ezku and I have been pretty firm on our positions, I think that arborint simply withdrew.

    That said, I think that this thread is more and more evolving into a regular framework, than the pick-and-choose library it started out as. That is probably natural and may be good in itself, but I think it makes a difference.

    I might want to explore that direction further, if some of you are interested in joining forces ?

  3. #128
    SitePoint Guru
    Join Date
    May 2005
    Location
    Finland
    Posts
    608
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by kyberfabrikken
    Arborint, who have been a driving force in the thread, obviously disapproves on the current design of the ApplicationController, which on the other hand, Ezku and I have been quite happy about. Since Ezku and I have been pretty firm on our positions, I think that arborint simply withdrew.
    Really? I was in the belief that he only disagreed on the InputProcessor part, which really is more a matter of implementation. I think the point in that whole escapade was to provide something rudimentary but extendable in order to have something for the ApplicationController to work on, not as to dictate what kind of validation process the AC should work with.

    If arborint's still around, I do have interest in his state machine approach and would be extremely delighted seeing it evolve.

  4. #129
    Non-Member
    Join Date
    Jan 2003
    Posts
    5,748
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    PHP Code:
    // ...
    class HttpRequest extends DataSpace
    {
    // ... 
    Then you have this in one of the class constructor as well,

    PHP Code:
    // ...
    $this->GET = new DataSpace($_GET);
            
    $this->POST = new DataSpace($_POST);
    // ... 
    What is the point of having one class extend this DataSpace, and then having to create 2 instances of this same class for variable purposes? What is the responsiblity of DataSpace?

    I'm lost as to what your trying to do. Also, for $_FILES, I don't see how this has actually got anything to do with a Request object of any kind either. If you require access to $_FILES then do so under it's own responsibility as well.

    When I think about it some more, the whole class hierarchy has just lost me, I have absolutely no idea what the purpose of Request, Response, HttpRequest, HttpResponse are? Their responsiblities are all inter mixed and it's misleading

    I still think you need to work on it some more

    If you do intend to use a Context object of some sort, it should encapsulate both a Request and a Response object (the approach I use, but I don't refer to as a Context), as their dual responsibilities are clearly apparent no?

    Failing that, then there is no point in continueing with it. Anyways, what is the current situation with this discussion, and is there any new script to be viewed, not including the examples already posted...

    Anything concrete that will run on my server at home?

  5. #130
    SitePoint Wizard
    Join Date
    Aug 2004
    Location
    California
    Posts
    1,672
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by kyberfabrikken
    Arborint, who have been a driving force in the thread, obviously disapproves on the current design of the ApplicationController, which on the other hand, Ezku and I have been quite happy about. Since Ezku and I have been pretty firm on our positions, I think that arborint simply withdrew.
    Quote Originally Posted by Ezku
    If arborint's still around, I do have interest in his state machine approach and would be extremely delighted seeing it evolve.
    I'm still around and have been experimenting along my own track trying to get some time to put together some better examples.

    I think where we went different directions is on how the information from the request gets to the controllers. At some point it may be a question of style, but I am not that interested in the contortions that adding a Context class requires. You might as well use a general Locator which would simplify things. But that makes it then difficult to mix and match these classes with other classes that do not use the Locator (as does the Context in my opinion). If you can get it to work in a clean way I think it would be very interesting.

    I'm heading in the direction that assumes that once I get to the Application Controller I need more than the Request can provide so I abandon it. From that point on have the controllers maintain a list of objects that can contain all the associated data that goes with each field.

    At this point I think I need to start working backwards from a real application to see what the Applicaiton Controller needs to provide from the application interface point of view.

    There are a few classes that would be helpful for writing example apps for these "skeleton" classes, so if anyone has very, very, very basic versions (under 5Kb of code each) of the following classes please post them for use in example apps. Think of it as a coding challenge to see who can code the simplest, cleanest, smallest utility classes to the "skeleton". Needed are:

    • ultra basic Template class (load file, bind and str_replace or eval is probably enough)


    • Session DataSpace Singleton


    • Form Field Generator class (you know: multi select, radio, checkbox, plus text, textarea, hidden). I don't care that much about form, submit, reset, etc. because those can just be in the template. It's really select, radio, checkbox that are necessary because the need to generate the selected/checked settings based on existing data. But I guess it is good to have the full set for compelteness.


    If we could get those three classes we could probably code up some real world examples.
    Christopher

  6. #131
    SitePoint Guru
    Join Date
    May 2005
    Location
    Finland
    Posts
    608
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by arborint
    I'm still around and have been experimenting along my own track trying to get some time to put together some better examples.
    I'm glad.

    I don't quite understand all your points, though. Probably just my lack of experience.
    • ultra basic Template class (load file, bind and str_replace or eval is probably enough)
    • Session DataSpace Singleton
    Along the lines of these, or did I miss something?
    PHP Code:
    /**
     * Simple templating class.
     * 
     * @author        Ezku (dmnEe0@gmail.com)
     * @since        Jul 19, 2005
     */
    class Template
    {
        protected 
    $templates = array();
        protected 
    $vars = array();
        protected 
    $root NULL;
        
        
    /**
         * Assign template variable
         * @param    string    variable name
         * @param    mixed    variable value
         */
        
    public function assign($name$value)
        {
            
    $this->vars[$name] = $value;
        }
        
        
    /**
         * Add template to the stack.
         * @param    string    filename
         */
        
    public function add($template)
        {
            
    $this->templates[] = $template;
        }
        
        
    /**
         * Set template root directory.
         * @param    string    path
         */
        
    public function setRoot($path)
        {
            
    $this->root $path;
        }
        
        
    /**
         * Clear template stack.
         */
        
    public function clear()
        {
            
    $this->templates NULL;
            
    $this->templates = array();
        }
        
        
    /**
         * Render templates, clearing the stack.
         */
        
    public function render()
        {
            foreach(
    $this->templates as $template)
            {
                include 
    $this->root.$template;
            }
            
    $this->clear();
        }

    PHP Code:
    /**
     * @author        Ezku (dmnEe0@gmail.com)
     * @since        Jul 19, 2005
     */
    class SessionDataSpace extends DataSpace
    {
        static protected 
    $instance NULL;
        
        protected function 
    __construct()
        {
            
    $this->import($_SESSION);
        }
        
        public function 
    __destruct()
        {
            
    $_SESSION array_merge($_SESSION$this->all());
        }
        
        static public function 
    getInstance()
        {
            if(!(
    self::$instance instanceof self))
            {
                
    self::$instance = new self;
            }
            return 
    self::$instance;
        }


  7. #132
    SitePoint Wizard
    Join Date
    Aug 2004
    Location
    California
    Posts
    1,672
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Dr Livingston
    Anything concrete that will run on my server at home?
    I would like to build some real application examples to show how the different ideas and code in the thread (and the Front Controller one) can be applied. That's why I asked for a couple of utility contributions to the codebase above. I would like to build some demonstration code to show controller based example app containing a plain page, a simple form and a multi-forms/pages sequence.
    Christopher

  8. #133
    SitePoint Wizard
    Join Date
    Aug 2004
    Location
    California
    Posts
    1,672
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Ezku
    Along the lines of these, or did I miss something?
    Close.

    For Template: A str_replace() one that just used HTML templates might be simpler. If we want to go the route of PHP templates then using extract() and output buffering to capture into a string to hand off to another template or the Response. Though you could probably have both renderStr() and renderEval() as they are such small functions.

    The Session one should allow direct read/write access to the session. I'm not sure the one you posted does because it imports the session data.

    {Probably also PHP4-ize them so more people can run them)
    Christopher

  9. #134
    SitePoint Guru
    Join Date
    May 2005
    Location
    Finland
    Posts
    608
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by arborint
    For Template: A str_replace() one that just used HTML templates might be simpler. If we want to go the route of PHP templates then using extract() and output buffering to capture into a string to hand off to another template or the Response. Though you could probably have both renderStr() and renderEval() as they are such small functions.

    The Session one should allow direct read/write access to the session. I'm not sure the one you posted does because it imports the session data.
    I hate to say this, but I'm at a complete loss here. What's an "str_replace() Template"? There's gotta be display logic in the templates and that's most simply done using native PHP. What's wrong with "caching" the Session data in the object and only writing it back on destruction? Not to say my implementation is correct (doesn't even run), but the concept should be fine.
    Edit:

    Nope. http://fi2.php.net/manual/en/ref.session.php: Session data is not available to an object's __destruct method as sessions are closed before the object is 'destroyed'. So how do you do this elegantly? Main-level $context->session->persist()?

  10. #135
    SitePoint Zealot
    Join Date
    Jul 2005
    Posts
    194
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hmm.. What's the status of this? :+ I am now using PHP5 so I might be able to tweak some of the ideas here in the upcoming project.

  11. #136
    SitePoint Wizard
    Join Date
    Aug 2004
    Location
    California
    Posts
    1,672
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Ezku
    I hate to say this, but I'm at a complete loss here. What's an "str_replace() Template"? There's gotta be display logic in the templates and that's most simply done using native PHP.
    I don't think we want a Template class to output. We just want it to render the values into the template and return the result. Then we can either feed it to another template or pass it to the Response which will render it (if no redirect is pending).
    Quote Originally Posted by Ezku
    What's wrong with "caching" the Session data in the object and only writing it back on destruction? Not to say my implementation is correct (doesn't even run), but the concept should be fine.
    Nothing is necessarily wrong with it. Just more code and it requires the use of a more complex DataSpace class than the basic get/set one. I don't remember exactly how to do PHP4 Singletons, maybe just:
    PHP Code:
    class Session extends DataSpace {
        
        function 
    DataSpace() {
            
    $this->data =& $_SESSION;
        }
        
        function 
    getInstance() {
             static 
    $instance;
             if(! 
    $instance) {
                 
    $instance =& new Session();
             }
             return 
    $instance;
       }

    Christopher

  12. #137
    SitePoint Guru
    Join Date
    May 2005
    Location
    Finland
    Posts
    608
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Off Topic:

    Seeing that my experience-lacking commentary seems to cause more trouble than it's worth, I'll try to refrain myself from messing around unless I really have something to say. I'm not exactly anyone you would want to be taught application design by.

  13. #138
    SitePoint Wizard
    Join Date
    Aug 2004
    Location
    California
    Posts
    1,672
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Ezku
    Seeing that my experience-lacking commentary seems to cause more trouble than it's worth, I'll try to refrain myself from messing around unless I really have something to say. I'm not exactly anyone you would want to be taught application design by.
    Refrain not. We're all learning here.
    Christopher

  14. #139
    SitePoint Guru
    Join Date
    May 2003
    Location
    virginia
    Posts
    988
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Just wondering if there is a final code archive of the "skeleton" framework?

  15. #140
    SitePoint Wizard
    Join Date
    Aug 2004
    Location
    California
    Posts
    1,672
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by mwmitchell
    Just wondering if there is a final code archive of the "skeleton" framework?
    We have been experimenting in two directions. There was code posted back in this thread by kyberfabrikken/ezku and by me. Both have functioning examples. I am trying to get some more real-world example pages together but need a few more utility classes to get there. kyberfabrikken or ezku can probably tell you better where they are at.
    Christopher

  16. #141
    SitePoint Zealot
    Join Date
    Jul 2005
    Posts
    194
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yeah, I am losing track of this project of you guys. Especially when the overall conversation is not printable. Because the print version is blanking out the PHP code parts.

  17. #142
    SitePoint Addict
    Join Date
    Jan 2005
    Location
    Ireland
    Posts
    349
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by wdeboer
    Yeah, I am losing track of this project of you guys. Especially when the overall conversation is not printable. Because the print version is blanking out the PHP code parts.
    Yeah, thank god a new thread was started from the Front Controller.

    Make sure you have checked out the Front Controller, which was done before this. It might make it easier then to understand what they are trying to achieve in this thread.

    arborint: A very basic (and rough) Template class. (completely untested, and I don't mean unit tests, I mean no even interpetated. Don't have access to an interpetator at the moment)

    PHP Code:
    <?php
    class Template
    {
        var 
    $templates = array();
        var 
    $vars = array();
        var 
    $root_dir '';
        
        
    /**
         * Adds a variable to the variable array
         * @param    string    property
         * @param    mixed    value
         */
        
    function addVar($property$value) {
            
    $this->vars[$property] = $value;
        }
        
        
    /**
         * Adds an associative array of variables to the variable array (variable name/variable value equivalent to the array key => value)
         * @param    array    variables
         */
        
    function addVars($vars) {
            
    $this->vars array_merge($this->vars$vars);
        }
        
        
    /**
         * Adds to the template queque
         * @param    string    template file
         */
        
    function addTemplate($tpl) {
            
    $tpl $this->root_dir '/'$tpl;
            if (
    file_exists($this->root_dir '/'$tpl)) {
                
    $this->templates[] = $tpl;
                return 
    true;
            }
            
    // Better error-handling obviously neccessary, but this only an example.
            
    trigger_error("The template file $tpl does not exist.");
            return 
    false;
        }
        
        
    /**
          * Sets the root directory for template files.
          * @param    string    template root directory
          */
        
    function setRoot($path) {
            
    $this->root_dir $path;
        }
        
            
        
    /**
         * Clear template queque and variable array
         */
        
    function clear() {
            
    $this->vars = array();
            
    $this->templates = array();
        }
        
    /**
         * Renders the templates
         */
        
    function render() {
            
    // Pollute the namespace with our variables
            
    extract($this->vars);
            
    ob_start();
            foreach(
    $this->templates as $template) {
                include(
    $template);
            }
            return 
    ob_get_clean();
        }
    }
    ?>
    I didn't do a string_replace based template simply because then a templating language would need to be defined. That is okay if all we are doing is variable substition, but I don't want to be making control structures (like loops) or compiling, etc, etc. I think it would be better to simply show php-templates for basic examples, that way the class stays simple, and no-one has to learn (I know, it only takes 2 seconds ) a templating language.

  18. #143
    SitePoint Wizard silver trophy kyberfabrikken's Avatar
    Join Date
    Jun 2004
    Location
    Copenhagen, Denmark
    Posts
    6,157
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Wow. That kicked something off.

    Quote Originally Posted by arborint
    ultra basic Template class
    I don't really see the need for a template. Templates are one way to solve View-Controller seperation. Another strategy is to use a DispatcherView coupled with ViewHelpers. This is what I prefer.

    Quote Originally Posted by arborint
    Session DataSpace Singleton
    Ezku's SessionDataSpace will work, but wouldn't this be better :
    PHP Code:
    class SessionDataSpace extends DataSpace
    {
        function 
    SessionDataSpace($name) {
            
    // start session if needed
            
    if (session_id() == "") {
                
    session_start();
            }
            
    // init session-data, if needed
            
    if (!isset($_SESSION[$name])) {
                
    $_SESSION[$name] = Array();
            }
            
    // attatch the dataspace to the session-data
            
    $this->_data =& $_SESSION[$name];
        }

    The difference between the two implementations mainly beeing that #1 is a Singleton, since it refers directly to the global var $_SESSION, while #2 allows for seperate objects within the same session.

    Quote Originally Posted by mwmitchell
    Just wondering if there is a final code archive of the "skeleton" framework?
    We'd likely post to the CVS at sourceforge at some point. Right now however, we have different ideas of how to do stuff though.

  19. #144
    SitePoint Guru 33degrees's Avatar
    Join Date
    May 2005
    Posts
    707
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by kyberfabrikken
    Right now however, we have different ideas of how to do stuff though.
    As other people have mentioned, I think it's perfectly appropriate to persue several directions at once; the advantages of one approach over another may only become apparent once concrete implementations are in place, and in the end different approaches may be good for different problems.

    We do, however, have to agree on this request/context thing. I personally vote for keeping the existing request and response objects and placing sessions and logging in them where appropriate. It's a tried and true approach... in any case, once we have these objects named and implemented, I think the rest will be a fair bit easier.

  20. #145
    SitePoint Wizard
    Join Date
    Aug 2004
    Location
    California
    Posts
    1,672
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by kyberfabrikken
    I don't really see the need for a template. Templates are one way to solve View-Controller seperation. Another strategy is to use a DispatcherView coupled with ViewHelpers. This is what I prefer.
    Yes, I know that it is not a necessary part of this, but it is a very common implementation that I think will make examples clearer. Dispatcher View still uses a Template. It just adds a View Helper as an Adapter to the Model.
    Quote Originally Posted by kyberfabrikken
    but wouldn't this be better :
    PHP Code:
    class SessionDataSpace extends DataSpace
    {
        function 
    SessionDataSpace($name) {
            
    // start session if needed
            
    if (session_id() == "") {
                
    session_start();
            }
            
    // init session-data, if needed
            
    if (!isset($_SESSION[$name])) {
                
    $_SESSION[$name] = Array();
            }
            
    // attatch the dataspace to the session-data
            
    $this->_data =& $_SESSION[$name];
        }

    The difference between the two implementations mainly beeing that #1 is a Singleton, since it refers directly to the global var $_SESSION, while #2 allows for seperate objects within the same session.
    The one you posted does not provide access to the entire $_SESSION, but only to $_SESSION[$name]. I think it will need to be separate from DataSpace because (as I recall) $this->_data =& $_SESSION; does not work.
    Quote Originally Posted by kyberfabrikken
    We'd likely post to the CVS at sourceforge at some point. Right now however, we have different ideas of how to do stuff though.
    There is no reason we could not post both as well. I think some of the supporting classes might have diverged a little too far at this point.

    As I said, I am trying to build some examples that are more like a real app so I can see if the direction I am headed actually makes sense. That's why I asked for the Session, Template and Form Field classes. With those you can build an actual little multi-form example.
    Christopher

  21. #146
    SitePoint Zealot
    Join Date
    Jul 2005
    Posts
    194
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Just a basic form generator, nothing shocking. The idea behind is that your register formElements instances into the formStorageModel wich will keep track of all the elements for the form. The form decorator will used to render all the controls, as you each formelement has it's own renderer. I am not really convinced it's good, but... should work for now.

    Keep in my mind that this is not tested.

    PHP Code:
    class FormElement {
        var 
    $name// equals ID
        
    var $value;
        
        function 
    FormElement() {
              
    trigger_error'The FormElement::FormElement() needs to be overriden.'E_USER_ERROR );
        }

        function 
    setName$value ) {
             if ( 
    $this->name !== $value $this->name $value;
        }

        function 
    setValue$value ) {
             if ( 
    $this->value !== $value $this->value $value;
        }
     
        function 
    getName() {
             return 
    $this->name;
        }

        function 
    getValue() {
             return 
    $this->value;
        }
       
        function 
    render() {
              
    trigger_error'The FormElement::Render() needs to be overriden.'E_USER_ERROR );
        }
    }


    class 
    FormStorageModel {
       var 
    $elements;

       function 
    FormGenerator($name='') {
            
    $this->elements = array();
            
    $this->setName$name );
       }

       function 
    getElementsCount() {
         return 
    count$this->elements );
       }

        function 
    setName$value ) {
             if ( 
    $this->name !== $value $this->name $value;
        }

        function 
    getName() {
             return 
    $this->name;
        }

        function 
    registerElement( &$formElement ) {
             
    // check if the getName() is available and if it the key/name exists already in the elements array
             
    $this->elements[] =& $formElement;
        }

        function 
    removeElementByName$name ) {
             
    // remove code, never know this stuff  out of my head :)
        
    }

        
    functon getFormElements() {
             return &
    $this->elements;
        }
    }


    class 
    FormDecorator {
         var 
    $formStorage;

         function 
    FormDecoratorr( &$formModel=NULL ) {
             
    $this->formStorage =& $formModel;
         }

         function 
    getOutput() {
                
    // output the stuff
               
    if ( $this->formStorage->getElementsCount() <= ) {
                     
    trigger_error'No form elements available to decorate!'E_USER_WARNING );
                     return 
    FALSE;
               }

               
    // echo '<form>';
               
    echo '<!-- Automatically generated form: ' $this->getName() . ' -->';
               
    $formElements =& $this->formStorage->getFormElements();
               foreach( 
    $formElements as $elementName => $element ) {
                     
    $element->render(); // the FormElement outputs the control 
               
    }
               echo 
    '<!-- End of automatically generated form -->';
               
    // echo '</form>';
         
    }
    }


    // simple example :P
    class TextFormElement extends FormElement {
         
           function 
    TextFormElement() { }

           function 
    render() {
                
    // requires to be overriden otherwise a error message will be shown
                
    echo '<input type="text" name="' $this->getName() . "' id="' . $this->getName() .  '" />'; 
           }

    Hope you guys like it a bit :+

  22. #147
    SitePoint Wizard silver trophy kyberfabrikken's Avatar
    Join Date
    Jun 2004
    Location
    Copenhagen, Denmark
    Posts
    6,157
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by arborint
    The one you posted does not provide access to the entire $_SESSION, but only to $_SESSION[$name].
    Yep. The point exactly. The one I posted will allow you to create multiple named dataspaces throughout the application, which will persist between sessions.

  23. #148
    SitePoint Guru
    Join Date
    May 2005
    Location
    Finland
    Posts
    608
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by kyberfabrikken
    Yep. The point exactly. The one I posted will allow you to create multiple named dataspaces throughout the application, which will persist between sessions.
    And something like this won't?
    PHP Code:
    /**
     * Handle sessions by wrapping a Singleton DataSpace populated with $_SESSION.
     * 
     * @author        Ezku (dmnEe0@gmail.com)
     * @since        Jul 19, 2005
     */
    class Session
    {
        static protected 
    $dataspace NULL
        
        public function 
    __construct()
        {
            
    $this->init();
        }
        
        
    /**
         * Start session and populate data.
         */
        
    public function init()
        {
            if (!(
    self::$dataspace instanceof DataSpace))
            {
                
    session_start();
                
    self::$dataspace = new DataSpace($_SESSION);
            }
        }
        
        
    /**
         * Persist data and close session.
         */
        
    public function commit()
        {
            if(
    self::$dataspace instanceof DataSpace)
            {
                
    $_SESSION array_merge($_SESSIONself::$dataspace->all());
                
    session_write_close();
                
    self::$dataspace NULL;
            }
        }
        
        
    /**
         * Method calls and variable gets and sets fall through to DataSpace
         */
         
        
    public function __call($method$args) { return call_user_func_array(array(self::$dataspace$method), $args); }
        public function 
    __get($name) { return self::$dataspace->$name; }
        public function 
    __set($name$value) { self::$dataspace->$name $value; }

    Now, let's create those multiple named dataspaces:
    PHP Code:
    $context->session->foo = new DataSpace;
    $context->session->bar = new DataSpace;

    // You can do this, too:
    $session = new Session;
    $session->foo = new DataSpace;
    $session->bar = new DataSpace
    Wasn't that easy?

    I guess my point is that these two aren't mutually exclusive. You could create a PersistentDataSpace that would take advantage of the Session class. Something like this should do it:
    PHP Code:
    class PersistentDataSpace extends DataSpace
    {
        public function 
    __construct($name)
        {
            
    $session = new Session;
            if (!empty(
    $session->$name))
            {
                
    $this->import($session->$name);
            }
            
    $session->$name $this;
        }


  24. #149
    SitePoint Wizard
    Join Date
    Aug 2004
    Location
    California
    Posts
    1,672
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by kyberfabrikken
    Yep. The point exactly. The one I posted will allow you to create multiple named dataspaces throughout the application, which will persist between sessions.
    I haven't followed where you have taken the DataSpace class. I was just looking around the web for ideas and combined some things I found into the somewhat kooky code below.

    This DataSpace allows for paths into the dataspace array. The problem with this code is that uses eval() so there might be some security issues, but I think because the paths all come from the programmer it is ok.
    PHP Code:
    class DataSpace {
        var 
    $data = array();
        var 
    $source '$this->data';
        var 
    $delimiter '.';

        function 
    set($path$value) {
            eval(
    $this->source '[\'' str_replace($this->delimiter"']['"$path) . '\'] = $value;');
        }

        function 
    get($path) {
            
    $str $this->source '[\'' str_replace($this->delimiter"']['"$path) . '\']';
            eval(
    "\$value = (isset($str) ? $str : null);");
            return 
    $value;
        }

    I took the code from the Session class above but changed it so it doesn't start the session until a value is actually accessed. This is so you can still create a session object early and not have sent headers already which I have found to be a problem with things like upload pages.
    PHP Code:
    class Session extends DataSpace {
        
        function 
    Session() {
            
    $this->source '$_SESSION';
        }

        function 
    get($name) {
            if (
    session_id() == "") {
                
    session_start();
            }
            return 
    parent::get($name);
        }

        function 
    set($name$value) {
            if (
    session_id() == "") {
                
    session_start();
            }
            
    parent::set($name$value);
        }


    You can use it with the '.' delimeter Java/WACT style (or set your own delimeter if you want):
    PHP Code:
    $session =& new Session();
    $session->set('products.SKU123.color''blue');
    $session->set('products.SKU123.price'9.95);

    $sku $session->get('products.SKU123');
    // returns array('color'=>'blue', 'price'=>9.95) 
    Christopher

  25. #150
    SitePoint Wizard
    Join Date
    Aug 2004
    Location
    California
    Posts
    1,672
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    And while I'm at it, here is the simplest Template code I could come up with. It separates the bind code from the renderer so you can build other renderers, add caching, etc.
    PHP Code:
    class Template {
        var 
    $filename '';
        var 
    $vars = array();
        
        function 
    Template($filename='') {
            
    $this->setFilename($filename);
        }
        
        function 
    setFilename($filename) {
            
    $this->filename $filename;
        }
        
        function 
    bind($name$value) {
            
    $this->vars[$name] = $value;
        }
        
        function 
    clear() {
            
    $this->vars = array();
        }
        

    Here is a PHP template renderer that would use templates like "<title><?php echo $title; ?></title>".
    PHP Code:
    class TemplateEval extends Template {

        function 
    render() {
            
    extract($this->vars);
            
    ob_start();
            include(
    $this->filename);
            return(
    ob_get_clean());
        }


    Here is a str_replace() text template renderer that would use templates like "<title>{title}</title>".
    PHP Code:
    class TemplateStr extends Template {

        function 
    render() {
            
    $fp = @fopen($this->filename'r');
            if (
    $fp) {
                
    $template fread($fpfilesize($this->filename));
                
    fclose($fp);
            }
               
    $names array_keys($this->vars);
               return 
    str_replace($names$this->vars$template);
        }


    TemplateEval and TemplateStr sound like bad names, so maybe the name mavens can come up with better names for PHP and str_replace() templates. And should it be render() or parse()?
    Christopher


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
  •