PHP OOP using setter and getter methods on form elements - php

I'm coming from Java programming and I know a little when it comes with PHP OOP style. In Java Server Faces I got used with setters and getters which I use to set values of fields from data entered on form.
So for instance,
Person.java
Class Person{
private String firstname;
public setFirstName(String aFirstName){
this.firstname = aFirstName;
}
public getFirstName(){
return this.firstname;
}
}
PersonForm.xhtml
First Name: <input type="text" name="firstname" value="#{person.firstname}"/>
#{person.firstname} is what calls the setFirstName(); method from the class Person
So I did some google to see how it's done in PHPs OOP style.
So on PHP I thought it would look something like this.
Person.php
class Person{
private $firstname;
public function setFirstName($aFirstName){
$this->firstname = $aFirstName;
}
public function getFirstName(){
return $this->firstname;
}
}
PersonForm.php
<?php
$person = new $Person();
?>
<form>
First Name: <input type="text" name="firstname" value="<?php echo $person->firstname ?>"/>
</form>
I want to store the value entered on input text field using the setFirstName() method of Person class.
Does writing the value="<?php echo $person->firstname ?>" call the setFirstName() method?
Or should I do value="<?php echo $person->setFirstName() ?>"?
I'd appreciate any explanation or example.
PHPs OOP style is very similar with Java that's why I decided to study PHP using the OOP style instead of procedural.
Thank you.

Does writing the value="<?php echo $person->firstname ?>" call the setFirstName() method?
$firstname is a private property of Person class, so you can't access it outside of the class like that. And no, it won't call setFirstName() method.
Or should I do value="<?php echo $person->setFirstName() ?>"?
No, this will give you error since setFirstName() method is expecting an argument with the method call i.e. you're not passing any argument in this method, like $person->setFirstName('My first name'). Having said that, even though you do this, still you won't be able to set any user inputted first name unless you call this method with the user input value, like this: $person->setFirstName($_POST['firstname']);. Later, you can use getFirstName() method in your form to display the user inputted first name accordingly.
Here's a code example to accomplish your task,
PHP
class Person{
private $firstname = null;
public function setFirstName($aFirstName){
$this->firstname = $aFirstName;
}
public function getFirstName(){
return $this->firstname;
}
}
$person = new Person();
if(isset($_POST['submit'])){
$person->setFirstName($_POST['firstname']);
}
HTML
<form action="" method="post">
First Name: <input type="text" name="firstname" value="<?php if($person->getFirstName() != null){ echo $person->getFirstName(); } ?>"/>
<input type="submit" name="submit" value="Submit" />
</form>
The above example assumes that both HTML and PHP code should be on the same page.

You will be able to use the class you have defined inside the script being called by the form (at least that's the way I would do it).
person.html
<form action="savePerson.php" method="post">
First Name: <input type="text" name="firstname" id="firstname">
<button type="submit">Submit</button>
</form>
savePerson.php
<?php
class Person{
private $firstname;
public function setFirstName($aFirstName){
$this->firstname = $aFirstName;
}
public function getFirstName(){
return $this->firstname;
}
}
$person = new Person();
$person->setFirstName($_POST['firstname']);
//do something on the person object
?>

In this instance, you can't really declare the Firstname in the HTML form before it has been declared unless you already had this value stored somewhere else e.g. Database. You would need to use a client side language like Javascript to store and output data in real time. In terms of PHP, if you was making a call to a database or variable $aFirstName was predefined, your PHP would probably look something like this:
Person.php
class Person{
private $isSet; //Is Name Set on Object Creation
private $firstname;
public function __construct($aFirstName = false) { //Check if name is created on object creation.
if ($aFirstName === false) {
$this->isSet = false;
$this->firstname = 'No Data'; //Set so your field will always have predefined data.
} else {
$this->isSet = true;
$this->setFirstName($aFirstName);
}
}
private function setFirstName($aFirstName){
$this->firstname = $aFirstName;
}
public function getFirstName(){
return $this->firstname;
}
}
PersonForm.php
<?php //Check if Post data is set, if so then set name constructor
if (isset($_POST['firstname'])) {
$person = new Person($_POST['firstname']);
} else {
$person = new Person();
}
?>
<form method="post" action="">
First Name: <input type="text" name="firstname" value="<?php echo $person->getFirstName() ?>"/>
<input type="submit" value="submit">
</form>
This will output 'No Data' if the form input is not set or 'YOUR INSERTED DATA' if the value is set.

The important point to understand is PHP is working on server-side. So when you run your PHP script via a request it runs and finishes. When you hit that PersonForm.php script, it will generate the HTML document and send it to your browser, for example. That it there is no more chance to run PHP on your browser (frontend).
To store what is entered in a form you must use JavaScript/jQuery and make AJAX calls to a PHP script. So that JavaScript reads the form input and sends it to a PHP script on your backend, which will process the data like inserting it in a database etc.
I recommend you to read more about Javascript/jQuery and AJAX calls to achieve this.
A simple way to achieve it by using jQuery.
main.js
$("#submit").click(function(){
personName = $("input[name=firstname]").val();
$.ajax({
type: 'POST',
url: 'SavePerson.php',
data: {name: personName},
success: function(result, status, xhr) {
popup("Success!");
}
});
});
SavePerson.php
<?php
include_once('Person.php');
$person = new Person();
$person->setFirstName($_POST['name']);
// Do whatever you want with person...
?>
PersonForm.html
<!DOCTYPE html>
<html>
<form>
First Name: <input type="text" name="firstname" placeholder="Enter your name"/><br />
<button id="submit" value="Submit">Submit</button>
</form>
<script src='main.js'></script>
</html>

Related

How do I trigger/capture an event from my PHP generate HTML Code?

My class...
<?php
class SelectionBoxbuilder
{
public function RenderToHTML()
{
$SelectBox = '<select>
<option>"One"</option>
<option>"Two"</option>
</select>';
return $SelectBox;
}
}
My PHP test file that generates the selection box...
<?php
foreach (glob("classes/*.php") as $filename)
{
include $filename;
}
$sb = new SelectionBoxbuilder();
echo $sb->RenderToHTML();
This Works, but I need to know how to capture the event from the Selection box I have generated, not sure if I am in fact approaching this from the wrong angle perhaps I need to do this in an entirely different manner?
I basically want the event to trigger some other PHP code I have not written yet and pass the value of the selection box as a parameter.
Hope this I clear enough if not please let me know any additional information I could add.
So...
When the user changes the item selected on the selection box I would like this to trigger an event, which I will then 'point' to some other PHP code.
I am assuming that you are talking about change events on the select box (i.e. when the user selects a different value).
The main thing you need to understand is that the event is fired on the client side in the browser, while your PHP code is running on the server. It has no way of knowing what's happening on the client.
If you need to do something in PHP when these events are fired, you can add JavaScript code to handle the client-side event and to fire an AJAX request to your server-side PHP script.
In basicly PHP is a server side language.
So after the server side send output to browser you can't use PHP anymore.
To get the selection from user you need to make a new request to server.
You can do it by two methods:
Send the form data to server by regular http request (GET/POST).
Send data with ajax request for UX reasons.
First you need to change your "SelectionBoxbuilder" class to form element.
Like this:
<?php
class SelectionBoxbuilder{
public function RenderToHTML(){
$SelectBox = '
<form method="post">
<select name="selectbox">
<option value="1">"One"</option>
<option value="2">"Two"</option>
</select>
<br/>
<input type="submit" value="Send" />
</form>
';
return $SelectBox;
}
}
Now you have a form in you HTML output.
To get the response we need to add handler for the post request to the test file:
<?php
foreach (glob("classes/*.php") as $filename){
include $filename;
}
$sb = new SelectionBoxbuilder();
// If form submited
if( isset( $_POST['selectbox'] ) ){
echo 'Your selection is: ' . $_POST['selectbox'];
}
echo $sb->RenderToHTML();
You can add new method to your class to take care of the response:
<?php
class SelectionBoxbuilder{
public function RenderToHTML(){
$SelectBox = '
<form method="post">
<select name="selectbox">
<option value="1">"One"</option>
<option value="2">"Two"</option>
</select>
<br/>
<input type="submit" value="Send" />
</form>
';
return $SelectBox;
}
//Check response and return the value if form already submit
public function checkForResponse(){
if( isset( $_POST['selectbox'] ) ){
return 'Your selection is: ' . $_POST['selectbox'];
}
// return false if form not send
return false;
}
}
And now in test file you can do somthing like this:
<?php
foreach (glob("classes/*.php") as $filename){
include $filename;
}
$sb = new SelectionBoxbuilder();
// If form submited
if( $userAnswer = $sb -> checkForResponse() ){
echo 'Your selection is: ' . $userAnswer;
} else {
echo $sb->RenderToHTML();
}
I hope I was helpful to you.

Zend FrameWork - Form input from Layout to Controller

I have a small form, where user's can Subscribe to my newsletter.
How can i pass the email address from my Layout to my Controller?
My Layout name is Footer.phtml, here's the code:
<div id="subscribe">
<form name="newsletterRegister" method="post" action="">
<span>Subscribe to the Newsletter</span>
<input class="subscribeNewsletter" name="email" type="text">
<input id="subscribe_ok" type="image" src="/www/assets/newImages/footer/Ok.png" value="">
</form>
</div>
I have a controller called NewsletterController.php
I'm kinda lost with Zend Framework, can anyone help me figuring out what i have to do??
Well change this
<form name="newsletterRegister" method="post" action="">
To this
<form name="newsletterRegister" method="post" action="NewsletterController/YOURACTION">
And in your controller just get the data like this
$request = $this->getRequest();
$request->getPost()
If the action of your form is empty, it will post to itself.
But maybe you dont want to check on every page if the newsletter is send.
Try using a Controller Plugin, check the request object for the input field, name it unique like email_newsletter, if is not empty, do your logic.
File: application/plugins/Newsletter.php
class Application_Plugin_Newsletter extends Zend_Controller_Plugin_Abstract {
//before dispatching starts
public function preDispatch(Zend_Controller_Request_Abstract $request) {
$email = $request->getParam('email_newsletter',NULL);
if(!is_null($mail)) {
//check if is valid
if(Zend_Validate::is($email,'')) {
//do your logic
}
else {
//set some error messages
//maybe use helper flashMessenger
}
}
}
}
File: Bootrap.php
protected function _initPlugins() {
$this->bootstrap('frontController');
//Get FrontController Instance
$frontController = $this->getResource('frontController');
$frontController->registerPlugin(new Application_Plugin_Newsletter());
return $frontController;
}
OR
Set a form action like '/newsletter/subscribe'.
Then in controller 'newsletter' action 'subscribe' check the form and redirect to the sending page.
Maybe you should store sth like a last page visited to the session, or add a hidden input to that newsletter form, representing the current page you want to redirect to after the newsletter subscription is done.

How to assert form action attribute url with phpunit and selenium2?

I have a html form that has this markup.
<form id="login-form" action="/post/login">
<input name="username" type="text">
<input name="password" type="password">
</form>
I want to be able to assert this form action.
I try with this inside the test method, note I extended \PHPUnit_Extensions_Selenium2TestCase
$form = $this->byId('login-form');
$this->assertEqual('/post/login', $form->attribute('action'));
It seems like action always null.
Does anyone know how to test the form action attribute?
Thank you.
Unfortunately, $form->attribute('action') returns action with base url (http://localhost/post/login).
I did not find a way to get action without base and did not find how to get base url. There is my solution:
function testForm(){
$this->url('/test.html');
$form = $this->byId('login-form');
$this->assertEquals('/post/login', $this->getRelativeFormAction($form));
}
function getRelativeFormAction($form){
$action = $form->attribute('action');
$action = str_replace($this->getBaseUrl(), '', $action);
return $action;
}
function getBaseUrl(){
$urlComponents = parse_url($this->url());
$url = "{$urlComponents['scheme']}://{$urlComponents['host']}";
return $url;
}
There is successful full test code.

How do I make this object-oriented?

Currently I have the code below which registers a user.
It doesn't check to see if the username currently exists or anything like that, that is something that I want to implement.
I've never known how to use php objects and forms together. Any help will be much appreciated.
register.php
The page checks to see if a user is already logged in, either way the form is still displayed and submits to itself. The database access details are stored in config.php as constants.
<?php
session_start();
include("includes/config.php");
if(isset($_SESSION['username'])) {
echo "You are currently logged in as: " . $_SESSION['username'];
echo "<br />";
include("nav.php");
echo "<hr />";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
</head>
<body>
<?php
$odb = new PDO("mysql:host=" . DB_SERVER . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
if (isset($_POST['firstName'])) {
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$username = $_POST['username'];
$password = $_POST['password'];
$password = md5(DB_SALT.$password);
$type = $_POST['type'];
$date=date("Y-m-d");
$time=date("H:i:s");
$sql = "INSERT INTO tblMembers (firstName, lastName, username, passwordHash, type, joinedDate, joinedTime, lastActiveDate, lastActiveTime) VALUES (:firstName, :lastName, :username, :passwordHash, :type, :joinedDate, :joinedTime, :lastActiveDate, :lastActiveTime);";
$query = $odb->prepare($sql);
$results = $query->execute(array(
":firstName" => $firstName,
":lastName" => $lastName,
":username" => $username,
":passwordHash" => $password,
":type" => $type,
":joinedDate" => $date,
":joinedTime" => $time,
":lastActiveDate" => $date,
":lastActiveTime" =>$time
));
}
?>
<form method="post" action="">
Name: <input type="text" id="firstName" name="firstName" value="Michael" /><br />
Last Name: <input type="text" id="lastName" name="lastName" value="Norris" /><br />
Username: <input type="text" id="username" name="username" value="mstnorris" /><br />
Password: <input type="password" id="password" name="password" value="password" /><br />
Type: <input type="text" id="type" name="type" value="4" /><br />
<input type="submit" value="Add" />
</form>
</body>
</html>
I know how to write php objects using classes. This is what I had previously although I have been told that the methods I used are outdated. If anyone can shed any light on how to update it, it sure would help.
<?php
require_once("database.php");
class Member extends DatabaseObject {
protected static $table_name = "tblMembers";
var $firstName = "Mike"; // initiating the $firstName variable
var $lastName = "Norris"; // initiating the $lastName variable
var $username = "mstnorris"; // initiating the $username variable
var $password = "password"; // initiating the $password variable
var $reviews = "0"; // initiating the $reviews variable
var $type = "4"; // initiating the $type variable
function __construct($firstName, $lastName, $username, $password, $reviews, $type) {
$this->firstName = $firstName;
$this->lastName = $lastName;
$this->username = $username;
$this->password = $password;
$this->reviews = $reviews;
$this->type = $type;
//$this->insert($firstName, $lastName, $username, $password, $type);
}
function set_firstName($firstName) {
$this->firstName = $firstName;
}
function get_firstName() {
return $this->firstName;
}
function set_lastName($lastName) {
$this->lastName = $lastName;
}
function get_lastName() {
return $this->lastName;
}
function get_fullName() {
if (isset($this->firstName) && isset($this->lastName)) {
return $this->firstName . " " . $this->lastName;
} else {
return "";
}
}
function set_username($username) {
$this->username = $username;
}
function get_username() {
return $this->username;
}
function set_password($password) {
$this->password = md5(DB_SALT.$password);
}
function get_password() {
return $this->password;
}
public static function authenticate($username="", $password="") {
global $database;
$username = $database->escape_value($username);
$password = $database->escape_value($password);
$passwordHash = md5(DB_SALT.$password);
$sql = "SELECT * FROM tblMembers ";
$sql .= "WHERE username = '{$username}' ";
$sql .= "AND passwordHash = '{$passwordHash}' ";
$sql .= "LIMIT 1";
$result_array = self::find_by_sql($sql);
if (!empty($result_array)) {
//echo "true";
return array_shift($result_array); // Pulling first element from array
} else {
//echo "false";
return false; // Ability to ask whether we return something
}
}
public function insert($firstName, $lastName, $username, $password) {
$database = new Database();
$database->query("INSERT INTO tblMembers VALUES ('','{$firstName}','{$lastName}','{$username}','{$password}','4')");
}
// Common Database Methods
private static function instantiate($record) {
$object = new self;
foreach ($record as $attribute=>$value) {
if ($object->has_attribute($attribute)) {
$object->$attribute = $value;
}
}
return $object;
}
public static function find_all() {
return self::find_by_sql("SELECT * FROM ".self::$table_name);
}
public static function find_by_id($id=0) {
global $database;
$result_array = self::find_by_sql("SELECT * FROM ".self::$table_name." WHERE userID={$id} LIMIT 1");
if (!empty($result_array)) {
return array_shift($result_array); // Pulling first element from array
} else {
return false; // Ability to ask whether we return something
}
}
public static function find_by_sql($sql="") {
global $database;
$result_set = $database->query($sql);
$object_array = array();
while ($row = $database->fetch_array($result_set)) {
$object_array[] = self::instantiate($row);
}
return $object_array;
}
private function has_attribute($attribute) {
$object_vars = get_object_vars($this);
return array_key_exists($attribute, $object_vars);
}
}
?>
Can the MVC approach be used with AJAX? Also, with that in mind, the AJAX code I have used before in other projects use $_GET, is there any problems with this as the data is never being sent to the address bar? If so, how do I use $_POST with AJAX?
Mike:
your set a getter and a setter like this:
class Spam
{
public $attr;
public $var;
public $arg;
/* __construct, __set, and __get
these are all special functions
we know this from the double underscore */
function __construct ()
{
// construction code
}
function __set ( $arg0, $arg1 )
{
$this->$arg0 = $arg1;
}
function __get ( $arg )
{
return $this->$arg;
}
}
and you would call it from your code as follows:
// this calls the __constructor function
$barney = new Spam();
// this calls the __set function
$barney->attr = "garnished with spam & eggs";
// this calls the __get function
$attrValue = $barney->attr;
This reduces the need to call a different method to set/get the values of your variable. This will only work on public variables as private and protected variables cannot be accessed from outside of your class.
Also, it is a good idea to have separate views, models, and controllers. Your controller is the script that the form submits to, your model is the class that is instantiated, and your view is where the user sends the information from. This will make your code easier to understand, rather than having your controller and view together.
Are you restricted to PHP4 for some reason? Or did you download some really old code and you're now trying to get it to work?
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<[ UPDATE 2.27.2013 ]>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
OOP PHP Programming in Conjunction with JavaScript AJAX technology
Model-View-Controller:
MVC is not specific to PHP. MVC is a software design pattern that aims to solve a maintainability problem in code that combines separate
components of the code in ways that make the code less readable and
hard to maintain, which in the end is also a security risk.
Model-View-Controller is typically implemented via frameworks. In
regards to PHP there are frameworks available such as Zend,
CodeIgniter, CakePHP, etc. There frameworks implement the model view
controller through the document tree, although you can create your own
PHP framework (which isn't a good idea given your new to the
language), its probably better to use one that has already been
around. These frameworks may also enforce their own standards that result
in better code.
To understand a maintainable MVC framework you should be familiar with coding a website > > entirely in PHP. That means you should be using PHP classes [modules|models] to
dynamically generate the HTML pages[the view] depending what the user has done[the
controller file controls the model].
You question is very vague and its hard to tell what your asking, however, I get the
impression you're unable to figure out what MVC is and how to use it. Suppose you've
just created a layout for a website you will be developing. Since it
isn't possible to predict the size of your user's screen, you're
layout was designed in the browser. Your layout [or template if you
will] should be standard compliant HTML5 or XHTML. It should not be
constructed with images. Some people may disagree with me on this but
with the exception of your logo/header(though some use text for this
too), you should not have any tags are part of your
template(this is before any content has been written, obviously you'll
probably want to use a lot of images in your content). Your view at
this point should be HTML and CSS - any images that are a part of your
layout (ie patterns, backgrounds, anything layout specific) should be
in the CSS of your website. This is kind of the same reason that we
use the MVC pattern - it separates what should be separate.
You take your layout as the HTML and you write a PHP class[module]
that contains functions, for example we'll use
$view->showLeadboard();, $view->showAds(); $view->showFooter();
$view->setTitle("Title");, $view->setDescription("Description");...
This assumes that you've instantiated your class. Perhaps you don't
want to instantiate a class and you'd prefer to use static methods,
the choice is yours but you should understand what you're doing well
enough to have good reasons for doing it.
Now that your view is held inside of a PHP module you can worry about
your content. Chances are, if your website is dynamic, there will be
multiple pages and locations on those pages that contain dynamic
content from a database, or forms (we're still inside of the view)
that submit data to the controller.
Suppose somebody is registering at your website. The go to your
domain and a view is generated based on the request to
www.site.com and the view that is generated is the index page. This person who has come to your page has decided to register for an
account with your service. They click on the "register" hyperlink and
another view is generated that displays a form for them to create
their login credentials. They fill the form out click submit. The
information supplied in the form is submitted to a controller(we're
not talking about ajax or implementing an MVC design pattern for our
javascript code right now), we'll say that the view
site.com/register submits to the controller site.com/engine/process.php. Process.php filters/sanitizes the user data from the form and instantiates the correct class(model,
we'll call this one new User) that will then make a database
call through one of its methods, or maybe even through its
constructor(you should be aware of the magic methods available to you
in PHP) and this the result of this query mutates the view to be
slightly different depending on what the controller told the model and
what the model told the view.
I don't even know what I can say about your question regarding AJAX - given your position with PHP I'm going to guess that you're using JQuery for ajax calls. If this is the case you do not need to implement a model-view-controller from your jquery files, you can just create a jquery script and then add a method to your view that calls that script and implements it.
All in all if you are struggling to understand what a common pattern like MVC is and how to use it you should really go back to the basics. I can't stress enough that the online tutorials aren't going to help you if you don't understand why the author used the solution that they used and chances are they're not explaining that to you because its sometime simple that you should be able to understand yourself provided you have a basic understanding of the php language, its syntax, and how to solve problems with it. This all comes just from spending time with the language, learning how it works, and learning what it doesnt do well and what it does do well.
Ok, you have a couple of questions wrapped into one large question but I'll try to answer them as best as I can. I'll answer them in the order of importance.
How do you update your class(es).
How to structure forms better.
How to check login status.
Most applications now use some form of an MVC architecture. Models, Views, and Controllers are a way of separating responsibilities to classes. Here's a brief tutorial on MVC architecture for PHP. With that said, there are a number of open source frameworks that you can use like, Zend, CakePHP and more.
Try using one of the strategies for MVC or try a framework.
Try not to have the form self submit to itself. Instead route it to a seperate page and handle the logic there. Also you can wrap your inputs into and array by using the [] notation. For example: <input type="text" name="user[firstname]" />
However If you are just doing a login form, then all you need is some unique form of identification and a credential (e.g. username and password).
There are several ways to persist users' login status, chiefly used are sessions and cookies. Storing the entire model in the session or cookie is usually frowned upon. Instead try storing the username and a unique key that you can compare against in a database.
Using cookies gives you more control over how long you want the session to last.

Only show form if there is PHP

I'm new to PHP. Iv created a small php script. Basically I have a form and inside of it I have a function called show_sent:
<form method="post" action="contact.php" class="formstyle">
<h2>Formulaire de contact : </h2>
<p> </p>
<?
function show_sent(){
?>
<p>Sent</p>
<?
} // the function finishes here
?>
.......
I was hoping that it would only show the 'Sent' text when I call that function. How could I do this?
Thanks
contact.php is the same page as the form
You need to clean up your code a bit. Jumping into and out of HTML and PHP is not a good thing.
<?php
function show_sent() {
print "<p>Sent</p>";
}
if ($_POST) {
$errors = false;
/* logic to check data */
if (!$errors)
show_sent();
}
?>
<form>
<input type="text" name="fname" />
</form>
You need to check to see if the form data is posted. You do this by going:
if(isset($_POST['form_element_name']))
{
//call the show_sent function because data has been posted
show_sent();
}
or
function show_sent(){
if(isset($_POST['form_element_name']))
{
}
}
//Call the show_sent function all the time because the code inside the function checks the POST variables.
show_sent();
One way to do it is post the form to its self instead of another file then you can check if the variables have data in them and if they do call your sent function. check out this link for more info on post self.
http://www.webmaster-talk.com/php-forum/51903-php-self-submitting-form.html

Categories