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.

Need help, basic OOP

Discussion in 'PHP' started by scottlpool2003, Oct 17, 2012.

  1. #1
    Some of you regulars will notice I'm trying to learn OOP so please bare with me.

    I've gathered from all the tutorials I've seen that they're simply not working for me. I don't see the point in cars, houses or animals when I simply won't use them in my websites so I'm trying to just piece it together myself in ways that I would use it. I'm starting basic and will work up to using databases etc.

    Anyway, I decided that there's a bit of code I use to display error messages, usually I'd code this procedural and call out a variable.

    Here it is in the way I usually code:

    
    $class = "error";
    $themessage = "Error!</strong> You have already activated your account, please proceed to login.";
    
    PHP:
    OR

    
    $class = "success";
    $themessage = "Success!</strong> You successfully activated your account, please complete your signup.";
    
    PHP:
    To output
    echo "<div class=\"alerts\" style=\"width:90%;\"><div class=\"alert-message $class\"> <p><strong>$themessage</p><div class=\"close\">[x]</div></div></div>";
    
    PHP:
    Although this is reused, not much changes throughout the website other than the width or float, so how could I get this working so I can edit the class, message and style through OOP?

    So far I have:

    class.php
    <?php
    
    class Message {
    	
    	public function ShowSuccess() {
    		echo 'Logged in!<br />';
    		$type = 'success';
    	}
    	
    	public function ShowError() {
    		echo 'Not logged in!<br />';
    		$type = 'error';
    	}
    
    
    
    }
    
    ?>
    PHP:
    test.php
    <div class="alerts" style="width:500px;margin:0 auto;">  
    	<div class='alert-message error'>        
    	  <p>
    		<?php
    
    		$loggedin = 1;
    		$Message = new Message;
    		
    		if ($loggedin == 1){
    			$Message->ShowSuccess();
    		}
    		
    		else {
    			$Message->ShowError();
    		}
    		
    		?>
    	  </p>
    		<div class='close'>[x]</div>  
    	</div>
    </div>
    PHP:
    But I can't seem to figure out how to put the $type in this bit:
    <div class='alert-message error'>
    HTML:

     
    scottlpool2003, Oct 17, 2012 IP
  2. Wogan

    Wogan Peon

    Messages:
    81
    Likes Received:
    3
    Best Answers:
    2
    Trophy Points:
    0
    #2
    If you want anything inside your class to display, you're gonna have to echo it out from your class. You might want to try this:

    <?php
    
    class Message {
        
        public function ShowSuccess($string) {
            echo "<div class='alert-message success'>$string</div>";
        }
    
        public function ShowError($string) {
            echo "<div class='alert-message error'>$string</div>";
        }
    
    }
    
    PHP:
    And then to render it out:

    <div class="alerts" style="width:500px;margin:0 auto;">  
        <div class='alert-message error'>        
          <p>
            <?php
    
            $loggedin = 1;
            $Message = new Message;
            
            if ($loggedin == 1){
                $Message->ShowSuccess("Logged in successfully!");
            }
            
            else {
                $Message->ShowError("Error while logging in!");
            }
            
            ?>
          </p>
            <div class='close'>[x]</div>  
        </div>
    </div>
    PHP:
    There are ways to optimize it further, but that's the general idea :)
     
    Wogan, Oct 17, 2012 IP
  3. scottlpool2003

    scottlpool2003 Well-Known Member

    Messages:
    1,708
    Likes Received:
    49
    Best Answers:
    9
    Trophy Points:
    150
    #3
    But in terms of coding it in OOP would doing that not be quicker and easier to have a file called errors.php and code it entirely like

    if ($errormessage = 1){
    <div class="alert-message error">
    <p>
    Message Here
    </p>
    </div>
    }
    else {
    success message here
    }
    ?>
     
    scottlpool2003, Oct 18, 2012 IP
  4. Wogan

    Wogan Peon

    Messages:
    81
    Likes Received:
    3
    Best Answers:
    2
    Trophy Points:
    0
    #4
    It might be quicker and easier, but it wouldn't scale out very well if you relied on files for that sort of thing. Ideally, with OOP, you want to separate your business logic from your HTML as much as possible.

    So looking at your HTML, it looks like you have a div called "alerts" that should appear on the page, and can then be closed by clicking that [x]. In your PHP, you might do something like this - and I think I may be jumping the gun on quite a few concepts, so stop me if I'm moving too fast :)

    // Login postback handler (login.php)
    $App = new Application();
    
    if ($App->login($username, $password)) {
        $App->alert("Logged in Successfully");
    } else {
        $App->alert("Error while logging in! ");
    }
    
    $App->render('login');
    
    // class.application.php
    class Application {
        private $alerts; // To store any alerts
    
        public function login($username, $password){ /* Authentication logic here, return TRUE or FALSE */}
    
        public function alert($type, $string) {
            $this->alerts .= "<div class='$type'>$string</div>"; // Append the alert - we should actually be storing $type=>$string as an array and converting it to HTML later, but we'll cheat here for illustration purposes
        }
    
        public function template($page, $data=array()) {
    
            // Load the Template file
            $html = file_get_contents('templates/$page.tpl');
    
            // Run any substitions
            if (count($data) > 0) {
                foreach($data as $key => $value) {
                    $html = str_replace("{$key}", $value, $html);
                }
            }
    
            // Return the rendered HTML
            return $html;
        }
    
        public function render($page, $data=array()) {
    
            // Include our alerts
            $data['ALERTS'] = $this->alerts;
    
            // Render $page.tpl
            $html = $this->template($page, $data);
    
            // Echo out the HTML to the browser
            echo $html;
        }
    }
    PHP:
    <!-- login.tpl -->
    <div class='login'>
    <!-- your login form -->
    <!-- the alerts box -->
    <div class="alerts" style="width:500px;margin:0 auto;">{ALERTS}</div>
    </div>
    HTML:
    So here's how this all fits together:

    1. The user tries logging in, which causes a POST to login.php on your server
    2. login.php creates a new Application object (defined by class.application.php)
    3. The login() method is called, and takes the username and password, returning a TRUE or FALSE if the login succeeded or failed
    4. In both cases, the alert() method is called, which appends the alert HTML to the internal $alerts variable in the Application object
    5. render() is called, which loads the login HTML template, substitutes the {ALERTS} for the alert HTML and echoes it out.

    So now your application gets a little bit easier to scale out. You can call alerts() for any alert you can think of, and it will be rendered out on the next page load. You can call render() for any page you can think of, provided the .tpl file exists in the templates/ folder.
     
    Wogan, Oct 18, 2012 IP
  5. scottlpool2003

    scottlpool2003 Well-Known Member

    Messages:
    1,708
    Likes Received:
    49
    Best Answers:
    9
    Trophy Points:
    150
    #5
    Thanks for your thoughtful input.

    Probably a simple question but how is {alerts} called out? If it's being called from HTML it will only output {alerts} rather than the class...
     
    scottlpool2003, Oct 22, 2012 IP
  6. ThePHPMaster

    ThePHPMaster Well-Known Member

    Messages:
    737
    Likes Received:
    52
    Best Answers:
    33
    Trophy Points:
    150
    #6
    I would do it the same way as Wogan did, but with slight modifications in the abstraction of the MVC (the same way most MVC frameworks do it):

    
    class Application 
    {
        public function render($view, $data) 
        {
            foreach ($data as $var => $value) {
                $this->{$var} = $value;
            }
    
            if (file_exists("templates/{$view}.php") {
                include ("templates/{$view}.php");
            }
        }
    }
    
    $app = new Application();
    echo $app->render('login', array ('message' => 'Invalid login', 'type' => 'error'));
    echo $app->render('login', array ('message' => 'Login Success', 'type' => 'success'));
    
    PHP:
    And in the login.php file, I would do (it seems like you were using Twitter Boostrap, so I will post it instead of what Wogan posted):

    
    <div class="alerts" style="width:500px;margin:0 auto;">  
        <div class='alert-message <?php echo $type;?>'>        
          <p><?php echo $message;?></p>
            <div class='close'>[x]</div>  
        </div>
    </div>
    
    PHP:
     
    ThePHPMaster, Oct 22, 2012 IP