Tải bản đầy đủ (.pdf) (10 trang)

Thiết kế mạng xã hội với PHP - 8 pps

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (5.35 MB, 10 trang )

Planning and Developing the Core Framework
[ 52 ]
* @param String data : if the tag value = condition then extra tag
is replaced with this value
*/
public function addAdditionalParsingData($block, $tag, $condition,
$extratag, $data)
{
$this->apd[$block] = array($tag => array('condition' => $condition,
'tag' => $extratag, 'data' => $data));
}
We will want to get a list of all the template bits we need to process into the page
(processing is done by the template object).
/**
* Get the template bits to be entered into the page
* @return array the array of template tags and template file names
*/
public function getBits()
{
return $this->bits;
}
We also need to get our array of additional parsing data for the template handler
to process.
public function getAdditionalParsingData()
{
return $this->apd;
}
We often need to just access a specic loop block within our page; this method
makes this easy, by searching for us using regular expressions, and returning it.
/**
* Gets a chunk of page content


* @param String the tag wrapping the block ( <! START tag >
block <! END tag > )
* @return String the block of content
*/
public function getBlock( $tag )
{
//echo $tag;
preg_match (‚#<! START ‚. $tag . ‚ >(.+?)<! END ‚.
$tag . ‚ >#si', $this->content, $tor);
$tor = str_replace (‚<! START ‚. $tag . ‚ >', „", $tor[0]);
$tor = str_replace (‚<! END ‚ . $tag . ‚ >', „", $tor);

return $tor;
}
Download from Wow! eBook <www.wowebook.com>
Chapter 2
[ 53 ]
Obviously, we need to get the content from the page, so we use the
getContent method.
public function getContent()
{
return $this->content;
}
Finally, when we are ready to output the content to the browser, we do some nal
replacements. These are of template tags that we want to have in a template, but may
not always replace. One example is a registration form; if the submission has errors,
we would replace the form elds with the user's submission attempt. If, however,
the user is viewing the form for the rst time, they wouldn't want to see anything, so
we would either have to explicitly remove the template tags, or instead, prex them
with form_, and any leftovers are auto removed.

Once this is done, the content is returned to be output to the browser.
public function getContentToPrint()
{
$this->content = preg_replace ('#{form_(.+?)}#si', '',
$this->content);
$this->content = preg_replace ('#{nbd_(.+?)}#si', '',
$this->content);
$this->content = str_replace('</body>', '<! Generated by our
Fantastic Social Netowk >
</body>', $this->content );
return $this->content;
}
Authentication
In Chapter 3, Users, Registration, and Authentication, we will discuss how our user's
database will be structured, how we will manage the login and sign up process,
and how user authentication will work in general.
For now, we will leave this aspect out of our registry, and come back to it in the
next chapter.
URL processing
Since we are using a single frontend controller, we need to process the incoming
URL, in particular the page $_GET variable, to work out how to handle the users
request. This is generally done by breaking the variable down in parts, separated
by a forward slash.
Download from Wow! eBook <www.wowebook.com>
Planning and Developing the Core Framework
[ 54 ]
Manually setting the URL path is something we may need to do, so a simple setter
method is needed.
/**
* Set the URL path

* @param String the url path
*/
public function setURLPath($path)
{
$this->urlPath = $path;
}
The getURLData method processes the incoming URL, and breaks it down into parts,
building up an array of "URL bits".
/**
* Gets data from the current URL
* @return void
*/
public function getURLData()
{
$urldata = ( isset( $_GET['page'] ) ) ? $_GET['page'] : '' ;
$this->urlPath = $urldata;
if( $urldata == '' )
{
$this->urlBits[] = '';
$this->urlPath = '';
}
else
{
$data = explode( '/', $urldata );
while ( !empty( $data ) && strlen( reset( $data ) ) === 0 )
{
array_shift( $data );
}
while ( !empty( $data ) && strlen( end( $data ) ) === 0)
{

array_pop($data);
}
$this->urlBits = $this->array_trim( $data );
}
}
Download from Wow! eBook <www.wowebook.com>
Chapter 2
[ 55 ]
The rest of our social networks code needs to access the URL bits to determine what
they need to do, so we need a suitable get method.
public function getURLBits()
{
return $this->urlBits;
}
Similarly, we may need to have easy access to a specic bit. For example, if the
request is friends/view/ID, the rst bit would indicate that we use the friend's
controller; the friends controller would then use a switch statement against the
second URL bit, to work out what it needs to do.
public function getURLBit( $whichBit )
{
return ( isset( $this->urlBits[ $whichBit ] ) ) ?
$this->urlBits[ $whichBit ] : 0 ;
}
Another getter we need is to get the URL path.
public function getURLPath()
{
return $this->urlPath;
}
If we need to generate a URL, for instance, to build a link, or redirect the user, we
can make this easier with a helper function, which takes an array or URL $bits, any

additional information to go in the query string of the URL, $qs, and if the URL is an
administrative URL, $admin, (if it is, then it appends the administration directory to
the URL).
public function buildURL( $bits, $qs, $admin )
{
$admin = ( $admin == 1 ) ? $this->registry->getSetting('admin_
folder') . '/' : '';
$the_rest = '';
foreach( $bits as $bit )
{
$the_rest .= $bit . '/';
}
$the_rest = ( $qs != '' ) ? $the_rest . '?&' .$qs : $the_rest;
return $this->registry->getSetting('siteurl') . $admin . $the_rest;

}
Download from Wow! eBook <www.wowebook.com>
Planning and Developing the Core Framework
[ 56 ]
Extending the registry: potential new objects
There are many other features that we could add to our registry if we needed to
make it more powerful, including:
• Accessing the le system
• Enhancing security:
° Checking against a banned list
° Checking the format of certain data
• Generating and processing RSS feeds
Front Controller: single point of access
As we discussed earlier, we are going to implement the Front Controller pattern. This
will provide us with a single point of access to the framework powering Dino Space.

index.php
Our front controller is our index.php le. The rst thing we should do is call
session_start, as this needs to be done before anything is sent to the browser,
so by calling it rst, we know this will be the case.
session_start();
We should also dene a framework path constant, so if we are in another le
elsewhere, and we need to access a le relative to the framework path, we can
use this constant. Overuse of constants isn't recommended, however, and we
are only going to use them on occasions where appropriate.
DEFINE("FRAMEWORK_PATH", dirname( __FILE__ ) ."/" );
Next, we need to build our registry, and tell it which objects to create. As you can
see, the authenticate object is commented out, until we discuss this in Chapter 3.
require('registry/registry.class.php');
$registry = new Registry();
// setup our core registry objects
$registry->createAndStoreObject( 'template', 'template' );
$registry->createAndStoreObject( 'mysqldb', 'db' );
//$registry->createAndStoreObject( 'authenticate', 'authenticate' );
$registry->createAndStoreObject( 'urlprocessor', 'url' );
Download from Wow! eBook <www.wowebook.com>
Chapter 2
[ 57 ]
Next, we can include our conguration le, and connect to the database.
// database settings
include(FRAMEWORK_PATH . 'config.php');
// create a database connection
$registry->getObject('db')->newConnection( $configs['db_host_sn'],
$configs['db_user_sn'], $configs['db_pass_sn'],
$configs['db_name_sn']);
Now that we are connected to the database, we can look up any settings we have

in a suitable settings table, and store them in our registries settings array. This
should be for things like: administrators notication e-mail address, default view,
if certain features are enabled, and any API keys that we may need if we connect
to third-party services.
// store settings in our registry
$settingsSQL = "SELECT `key`, `value` FROM settings";
$registry->getObject('db')->executeQuery( $settingsSQL );
while( $setting = $registry->getObject('db')->getRows() )
{
$registry->storeSetting( $setting['value'], $setting['key'] );
}
The next stage would be to check if the user is logged in, build the default template,
and include the appropriate controller. We don't have any controllers at the moment,
and we haven't discussed how our models and controllers will work, so we will
leave those commented out for now, and return to them in Chapter 3.
// process authentication
// coming in chapter 3
/**
* Once we have some template files, we can build a default template
$registry->getObject('template')->buildFromTemplates('header.tpl.php',
'main.tpl.php', 'footer.tpl.php');
$registry->getObject('template')->parseOutput();
print $registry->getObject('template')->getPage()-
>getContentToPrint();
*/
?>
Download from Wow! eBook <www.wowebook.com>
Planning and Developing the Core Framework
[ 58 ]
.htaccess

We are routing all of our requests through our index.php le, and by passing
further information as the page $_GET parameter, this results in URLs which look
like: This isn't a
particularly nice looking URL, so we use the Apache
mod_rewrite module (which
most hosts have installed by default—if you use WAMPServer for development, you
may need to enable it in the Apache Modules menu), to take a nicer URL such as

/>, which eliminates the
need for ?page=, and translates it into the other format. This is rewritten by
dening a rewrite rule in a
.htaccess le within our code.
ErrorDocument 404 /index.php
DirectoryIndex index.php
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?page=$1 [L,QSA]
</IfModule>
Let's go through this le, line by line.
1. First, we tell Apache that the index.php le should deal with any 404 errors
(le not found).
2. The index.php le is the default le in the directory, so if someone visits the
folder on the web server with our site in, and doesn't specify a le, index.
php
is called automatically.
3. The IfModule block is conditional: the rules only apply if the module
mod_rewrite is installed.
4. If it is installed, we enable the rewrite engine.

5. If the user is trying to request a le, don't follow the rewrite rule (without
this, uploaded les and images wouldn't be displayed as even these requests
would be routed through our index.php le).
6. If the user is trying to access a directory that exists, then the rule isn't
followed again.
7. Finally, we have the rewrite rule, which takes the users request, and
interoperates it as the page $_GET parameter for our index.php le to
process. The rule takes everything from the URL (apart from the domain,
and any folders our site may be stored within) and appends it to the page get
variable. This line also takes any user-specied query strings (for example,
&someeld=somevalue) and appends it to the URL (QSA), and then ignores
other rules if that rule was used (L).
Download from Wow! eBook <www.wowebook.com>
Chapter 2
[ 59 ]
Summary
In this chapter, we have discussed a number of best practice techniques for designing
a framework to facilitate rapid development of our social networking website. This
included the Model-View-Controller architectural design pattern, the Registry
pattern, the Front Controller pattern, the Factory pattern, and we also discussed
the Singleton pattern.
We also discussed a suitable directory structure for our social networking site to use,
before building the core objects for our registry, and our front controller.
We now have a simple, lightweight framework that can help us rapidly develop
the rest of our social networking site. In the next chapter, we will look at
user registration, logging in, authentication (which will involve creating our
authentication registry object), and a controller to facilitate user registration.
Download from Wow! eBook <www.wowebook.com>
Download from Wow! eBook <www.wowebook.com>
Users, Registration, and

Authentication
With our basic framework in place, we are now able to start developing our social
networking site. The most important aspect of a social networking website is the
users; without users, we don't have a social network. In order to have users who
can use the site (overlooking marketing, and getting users to the site for the
moment), we need to be able to allow users to sign up, log in, and get the details
of a user who is currently logged in. We will also want to be able to manage
permissions of users, to see what they are permitted to do, and what they are
prohibited from doing on the site.
In this chapter, you will learn:
• Why privacy policies are important
• What core user data to store in the database
• How to extend user data to include prole data, without interfering
too much with our users table in the database
• Why you would want to implement a CAPTCHA system to prevent
automated signups
• The importance of privacy policies
• How to verify a user's e-mail address to prevent users signing up with
invalid e-mail addresses
• How to process user sign ups and logins, and to check whether a user
is a logged in user
• What to do when a user forgets their username or password
With this in place, we will have the rst major building block to our social
networking website—users!
Download from Wow! eBook <www.wowebook.com>

×