Archive for ◊ March, 2011 ◊

Author:
Monday, March 28th, 2011

This blog is related to Dynamically Applying styles to controls in control template of a button.

To do that one must override the OnApplyTemplate() of the control and use “GetTemplateChild(controlName)” within the method to access the control. There after,any dynamic style can be applied.

An Implementation example :

1) CustomButton class  which overrides OnApplytemplate and uses “GetTemplateChild” to access the border element

public class CustomButton : Button
    {
        public bool? IsSelected;
        public bool? IsNew;
        public string IconType;

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            Border border = GetTemplateChild(“border”) as Border;

            if (border != null)
            {
                border.BorderBrush = GetBorderBrush(IsSelected);
                border.Background = GetBackGroundStyleBasedOnType(IconType, IsNew);
            }
        }

        public Brush GetBackGroundStyleBasedOnType(string type,bool? isNew)
        {
            if (!string.IsNullOrEmpty(type))
            {
                switch (type.ToLower())
                {
                    case “default”:
                        if (isNew.HasValue && isNew.Value)
                            return Application.Current.Resources["MutationDefaultBackgroundBrush"] as Brush;
                        else
                            return Application.Current.Resources["MutationDefaultBackgroundBrush"] as Brush;
                 
                }
            }
            return null;
        }

        public Brush GetBorderBrush(bool? isSelected)
        {
            if (IsSelected.HasValue && IsSelected.Value)
            {
                return ThemeHelper.GetThemeBasedBrush(“MutationSelectedBrush”);
            }
            else
            {
                return ThemeHelper.GetThemeBasedBrush(“MutationUnSelectedBrush”);
            }
        }

    }
}

2) XAML Button Instantiation

 <local:MutationButton x:Name=”btnTerminatedSubscriptions” Style=”{StaticResource CustomButtonStyle}” Click=”btnTerminatedSubscriptions_Click”/>

 3) Style for button

 <Style x:Key=”MyButtonStyle” TargetType=”Button”>
        <Setter Property=”Template”>
            <Setter.Value>
                <ControlTemplate TargetType=”Button”>
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition/>
                        </Grid.ColumnDefinitions>
                        <Grid.RowDefinitions>
                            <RowDefinition />
                        </Grid.RowDefinitions>
                        <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup x:Name=”CommonStates”>
                                <VisualState x:Name=”Disabled”/>
                                <VisualState x:Name=”Normal”/>
                                <VisualState x:Name=”MouseOver”>
                                    <Storyboard>
                                        <ColorAnimation Duration=”0″ To=”#BFFFFFFF” Storyboard.TargetProperty=”(Border.Background).(GradientBrush.GradientStops)[1].(GradientStop.Color)” Storyboard.TargetName=”border” d:IsOptimized=”True”/>
                                        <ColorAnimation Duration=”0″ To=”#BF617584″ Storyboard.TargetProperty=”(Border.Background).(GradientBrush.GradientStops)[0].(GradientStop.Color)” Storyboard.TargetName=”border” d:IsOptimized=”True”/>
                                    </Storyboard>
                                </VisualState>
                                <VisualState x:Name=”Pressed”>
                                    <Storyboard>
                                        <ColorAnimation Duration=”0″ To=”#FFC4CFD8″ Storyboard.TargetProperty=”(Border.BorderBrush).(GradientBrush.GradientStops)[1].(GradientStop.Color)” Storyboard.TargetName=”border” d:IsOptimized=”True”/>
                                        <ColorAnimation Duration=”0″ To=”Black” Storyboard.TargetProperty=”(Border.BorderBrush).(GradientBrush.GradientStops)[0].(GradientStop.Color)” Storyboard.TargetName=”border” d:IsOptimized=”True”/>
                                    </Storyboard>
                                </VisualState>
                            </VisualStateGroup>
                            <VisualStateGroup x:Name=”FocusStates”>
                                <VisualState x:Name=”Unfocused”/>
                                <VisualState x:Name=”Focused”/>
                            </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>
                        <Border x:Name=”border” BorderThickness=”3″ CornerRadius=”5″ Grid.RowSpan=”1″ Grid.ColumnSpan=”1″ Grid.Column=”1″ Background=”{StaticResource MutationDefaultBackgroundBrush}” >
                            <Border.BorderBrush>
                                <LinearGradientBrush EndPoint=”0.5,1″ StartPoint=”0.5,0″>
                                    <GradientStop Color=”#7F000000″ Offset=”1″/>
                                    <GradientStop Color=”#7FC4CFD8″/>
                                </LinearGradientBrush>
                            </Border.BorderBrush>
                        </Border>
                        <ContentPresenter HorizontalAlignment=”Center” VerticalAlignment=”Center” RenderTransformOrigin=”0.2,0″ Grid.Column=”1″/>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        <Setter Property=”FontSize” Value=”18.667″/>
        <Setter Property=”Foreground” Value=”#7F000000″/>
        <Setter Property=”MinHeight” Value=”40″/>
        <Setter Property=”MinWidth” Value=”40″/>
    </Style>

Author:
Friday, March 25th, 2011

Well, I am not sure which category does this fall into, but I just realized today that its impossible to prove impossibility. Well just think of it. In my recent project, someone just mentioned that “it’s impossible to do this”.

Well how do you know??

We have tried every possible way??

How do you know if you have tried every possible way. You have only tried all possible ways you know of. But how do you claim, that, those were the only ways?? How do you know?

We can only prove something is not feasible in a certain way that we tried, but “proving impossibility is just impossible“.

Comments / disagreements are expected, but who cares :D … after all this is my personal opinion.

Category: General  | 7 Comments
Author:
Friday, March 25th, 2011

Currently I am reading this book called “Working Effectively With Legacy Code” by “Michael Feathers“. And the title of this post, “The “right” way to add a change may not be the best initial choice…”,  is taken from there. I could not stop myself from sharing this thought before keep on reading this book. What Michale is trying to say here of course is in context with writing tests for legacy code. First of all, lets understand, what is legacy code.

Legacy code normally is perceived by people as code that is written in past and mostly is there to be maintained because it still works. Although this definition is not complete. Legacy code is not “old” code.

  • Legacy code is any code that is without tests. So, if you are writing some code that does not have tests to prove its behavior, then you are creating legacy code today.
  • Legacy code is anything which takes a lot of time, sometimes non estimable, to change or to add new features in.
  • Legacy code is anything that you dare not touch because you are not sure if it will still work the way it was working yesterday.
  • Legacy code is anything that scares you when you look at it because, at the first look you don’t have any idea as to what is happening there.
  • Legacy code is anything that does not talk for itself and you need someone else who actually has written it to help you understand it.

In a nut shell, I would dare to say, Legacy code is anything that is smelling now.

But, before I can’t stop myself from going in this flow, I would like to stop and bring the focus back to the title of this post. If you really pay attention to the definition of legacy code above, we all know that we have seen legacy code. You are lying if you say no. Trust me, we all have got to deal with it most of our time.

But how do we do that? When we get a code that is full of legacy symptoms, we often find it hard to figure out where exactly to start. Now at this point, it becomes very important to start at least. When we start discussing ideas with our colleagues, we often find that the discussion goes into conversations like, “this is not the best way to do this” or “this can be done in this other way as well” etc etc. So which way do you take?

multiple ways

Of course yes, there can be ten different ways to do a particular thing. And may be many of them of equal quality. In that situation, what we need to focus on is, how many and what kind of changes does each of those re-factoring involve. Some methods may require the code to be changes drastically and some may not. Those which do not, may take a little less time. Then what should you do?

I think, the best can only be judged by the people on that code. You are the best person to take a call. But more often what has been seen is that, even though the easiest way may not be the best choice at the moment to remove a particular code smell, you can take it. The benefit that it may bring you that it may not fill the code with good fragrance, but it may reduce the smell a bit. So take the first step.

stepping-forward_legacy_code

And do remember that when you are doing these changes you make sure that those ares are test covered now. And if you continue this on couple of areas of the code base, it will create, what Michael Feathers call “islands of coverage“.

multiple_islands_of_ccoverage

And eventually these islands will merge to give a bigger and bigger island of covered code which is not smelling, or to say smelling lesser and lesser, and making it easier to take further steps towards eradicating the smells. Hopefully, you may find yourself, running in an island filled with good smell :D

no_smell_island

So, the idea is, its not necessary that the first step is definitely the best or even right choice, but if it helps you towards achieving something bigger, take it.

Your comments are welcome.

Author:
Thursday, March 24th, 2011

As a php developer you create lots of form in your application. But how do you track that the form submitted is submitted from your website.
This is how you spoof a form submission:
Lets assume we have following code located at http://www.yourdomain.com/form.php

<form action="submit.php" method="post">
<select name="myvar">
<option value="1">1</option>
<option value="2">2</option>
</select>
<input type="submit">
</form>

From the above code we notice that the value of $_POST[‘myvar’] is either 1 or 2.

Now if some one saves this form from their browser in their desktop, they can change action attribute to the full URL of the from .They can even replace select tag to textbox with the name ‘myvar’.

Now the modified form will be like this
<form action="http://yourdomain.com/submit.php" method="post">
<input type=”text” name=”myvar” value=”333333”>
<input type="submit">
</form>

Now this person can submit anything as the value of $_POST['myvar'].

The solution for this is to have a Shared secret . You can create a Secret key everytime the form loads and keep that key in a session. When you are submitting it you can also pass the session key as hidden variable. At the receiving end you can check if the hidden secret variable is same as the session variable .

$secret = md5(uniqid(rand(), true));
$_SESSION['secret'] = $secret;
<input type="hidden" name="secret" value="<php echo $secret;?>">

Category: PHP  | One Comment
Author:
Thursday, March 24th, 2011

First Let’s discuss about the issue of loading all the javascript files together at a stroke.

  1. 1. Javascript will not allow parallel download. So the browser will not start any other download until it loads the javascripts.
  2. 2. We use to load javascript files and methods which are unnecessary for that page. For eg: In Login page, we just need some javascripts essential for Login page, but developers will add all the javascripts in common headers.

<script language =”javascript” src=”scriptRequiredForUserProfile.js”></script>
<script language =”javascript” src=”scriptRequiredForAddComment.js”></script>
<script language =”javascript” src=”scriptRequiredForReply.js”></script>

<script language =”javascript” src=”scriptRequiredForAddComment.js”></script>

<script language =”javascript” src=”scriptRequiredForReply.js”></script>

How to solve the above 2 issues???

  • Include only one script in the header.

<script src="”loadJS.js”"></script>

Now we can load the javascript dynamically using 2 ways.

Method 1:

Generate dynamic // <![CDATA[
tag using DOM

Maintain the list of javascripts that you need to download for a respective page.

var jsFilesArray = new Array();
jsFilesArray['home.html'] = new Array( ‘validation.js’, ‘home.js’ );
jsFilesArray['login.html'] = new Array( ‘validation.js’, ‘error.js’ );

Code to get File Name of the current page

function getCurrentPageName() {
    var fileName = document.location.href;
    var end = (fileName.indexOf("?") == -1) ? fileName.length : fileName.indexOf("?");
    return fileName.substring(fileName.lastIndexOf("/")+1, end);
}

Code to generate dynamic tag and append to the head tag.

var head = document.getElementsByTagName("head")[0];

for (var i = 0;i<jsFilesArray[getFileName()].length;i++)
{
  script = document.createElement('script');
  script.id = "id_" + i;
  script.type = 'text/javascript';
  script.src = jsFilesArray[getCurrentPageName ()][i];
  head.appendChild(script);
}

Click to download the code.

Method 2:

Use AJAX to load the JS file dynamically whenever required

Get the required JS file using xmlHttPRequest and execute the output by passing it into eval() method. The eval() method executes the argument.

So guys, load your Javascripts dynamically and experience improved performance of your application.

Enjoy Coding :)

Author:
Thursday, March 24th, 2011

The are 2 main approaches to achieve this:

  1. UTL_SMTP: Available in Oracle 8i and 9i (for 10g use UTL_MAIL), is not easy to use to send emails with attached files but if you understand the concept of how the SMTP server handles this will be much easier. I will cover this below.
  2. Using Java, easier to send attachments but difficult to install and setup (you got to have access to user SYS in order to compile and run some functions in Java and also to run some commands to be able to compile the Java procedure)

In this article I will refer to the first approach, using UTL_STMP. I will save the Java approach for a later post in this blog.

How does SMTP work to send attachments?

What the SMTP server does in order to send an email with a text file attached it’s to get the text that arrives in one of the parameters or arguments passed to the function. The SMTP receives the text and encodes or decodes the text on the fly, depending if it’s sending or receiving the email. So when it arrives to your computer it’s when it gets ‘translated’ into a certain type of file.

This is the way that the process of sending a text attachment works. The SMTP server uses some commands to send the text and not the file itself. This means that contents when arrive to the destination will be stored as an attached file.

This is the reason why when sending an attached file it’s not needed to specify a path. You just pass the contents which will be encoded or decoded on the fly when receiving or sending the email.

How SMTP works using PL/SQL

Using UTL_SMTP to send mails with attachments

UTL_SMTP, as the name itself refers, it’s a utility Package included by default in Oracle Database since 8i release. It has some built in functions and procedures that basically provide an interface with the SMTP protocol commands. So the idea behind it is to interact with the SMTP server initiating and maintaining a conversation to achieve the functionality of sending emails from any stored procedure defined in PL/SQL

To implement this functionality inside your PL/SQL procedures, some functions have to be called; there is no need to initialize/setup the package because it comes pre-installed in the database server. Check the functions used, the parameters are self explanatory and the variables have to be declared previously.

Note that to send the attachment there is no need to call any specific function, the action of initializing some parameters, like the file name that will contain the attached text when the email it reaches its destination, is the only thing needed by the STMP server to send an email including text as an attachment.

-- initiate the conversation with the SMTP server, establishing the connection
v_smtp_connection := utl_smtp.open_connection( v_smtp_host, v_smtp_port );

-- perform a handshake with the SMTP server
utl_smtp.helo( v_smtp_connection, v_smtp_host );

-- sender (from) address
v_sender:= user@server.com

-- set the 'from' address of the message
utl_smtp.mail( v_smtp_connection, v_sender );

-- recipient (to) address
v_sender:= user@host.com

-- set the 'to' address of the message
utl_smtp.rcpt(v_smtp_connection, v_recipient);

-- send the email, using char(13) it's a way to pass the parameters to the SMTP server
utl_smtp.data(v_smtp_connection,'Single string message.' || Chr(13));

-- close the connection
UTL_SMTP.quit(l_mail_conn);

Sample Code

This code is to demonstrate the use of the UTL_SMTP package that is used in Warehouse Project .The text to be attached comes as a parameter to the function, it can hold up to 32768 characters long, if you need you can use a CLOB datatype which can handle up to 4 Gigs. There is also a place to name the file name that will hold the attached text once it reaches its destination.

The values To, Cc, Bcc are only used to display the recicpients of the email in a certain way in the email client (Hotmail, Eudora, Outlook, Yahoo, etc) . The values on this fields have nothing to do actually with the mechanism that sends the email as this fields are used only for representation purposes of how the recipients will be shown in each email client who will be used to read the email.

This function is commonly used in applications to send results from queries and it’s usually used inside a for cursor loop.

Function send_mail(
v_recipient varchar2, -- Field To of the email
v_subject varchar2, -- Subject of the email
v_body varchar2, -- Body of the email
v_attachment varchar2, -- Text that will be sent as an attached file
v_error_msg out varchar2) -- To hold the errors in the exception section

return boolean is

-- variable to hold the smtp server connection
v_smtp_connection utl_smtp.connection;

-- variable to hold the smtp host name
v_smtp_host varchar2(100) default 'my_smtp.com';

-- variable to hold the smtp port
v_smtp_port number default 25;

-- variable to hold the sender, from field
v_sender varchar2(100) default 'user@host.com';

begin

-- establish the connection to the smtp server
v_smtp_connection := utl_smtp.open_connection(v_smtp_host, v_smtp_port);

-- perform a handshake with the smtp server
utl_smtp.helo(v_smtp_connection, v_smtp_host);

-- set the 'from' address of the message
utl_smtp.mail(v_smtp_connection, v_sender);

-- add the recipient to the message
utl_smtp.rcpt(v_smtp_connection, v_recipient);

-- send the email
utl_smtp.data(v_smtp_connection,
'Date: ' || to_char(sysdate, 'DD-MON-YYYY HH24:MI:SS') || utl_tcp.crlf ||
'From: ' || v_sender || utl_tcp.crlf ||
'Subject: '|| v_subject || utl_tcp.crlf ||
'To: ' || v_recipient || utl_tcp.crlf ||
'Cc: ' || v_cc || utl_tcp.crlf ||

'MIME-Version: 1.0'|| utl_tcp.crlf || -- use Mime mail standard
'Content-Type: multipart/mixed;' || utl_tcp.crlf ||
' boundary="-----SECBOUND"'|| utl_tcp.crlf ||
utl_tcp.crlf ||

'-------SECBOUND'|| utl_tcp.crlf ||
'Content-Type: text/html;'|| utl_tcp.crlf ||
'Content-Transfer_Encoding: 8bit'|| utl_tcp.crlf ||
utl_tcp.crlf ||
v_body || utl_tcp.crlf || -- message body
utl_tcp.crlf ||

'-------SECBOUND'|| utl_tcp.crlf ||
'Content-Type: text/plain;' || utl_tcp.crlf ||
' name="error.log"'|| utl_tcp.crlf || -- file name that will hold the attached text
'Content-Transfer_Encoding: 8bit'|| utl_tcp.crlf ||
'Content-Disposition: attachment;'|| utl_tcp.crlf ||
' filename="error.log"'|| utl_tcp.crlf ||
utl_tcp.crlf ||
v_attachment || utl_tcp.crlf || -- attachment
utl_tcp.crlf ||

'-------SECBOUND--' -- end mime mail
);

-- end the connection to the smtp server
utl_smtp.quit(v_smtp_connection);

return true;

exception
when utl_smtp.invalid_operation then
v_error_msg := ' Invalid Operation in Mail attempt using UTL_SMTP.';
return false;
when utl_smtp.transient_error then
v_error_msg := ' Temporary e-mail issue - try again';
return false;
when utl_smtp.permanent_error then
v_error_msg := ' Permanent Error Encountered.';
return false;

end send_mail;

Category: Databases  | 4 Comments
Author:
Thursday, March 24th, 2011

Problem

Most Java 2 Platform, Enterprise Edition (J2EE) applications have a search and query requirement to search and list certain data. In some cases, such a search and query operation could yield results that can be quite large. It is impractical to return the full result set when the client’s requirements are to traverse the results, rather than process the complete set. Typically, a client uses the results of a query for read-only purposes, such as displaying the result list. Often, the client views only the first few matching records, and then may discard the remaining records and attempt a new query. [From Sun Developer Network]

Solution:

Pagination is the process of dividing information (content) into discrete pages. Pagination can be handled client-side or server-side. Server-side pagination is more common. Below image show a simple pagination:

social

Consider 20 records are shown per page.  How many records you fetch from database? 20 or complete result set or 20X10=200? Ideally you should restrict the fetch size to 200 for better performance.

Code snippet of EmployeeSearchValueListHandler:

public class EmployeeSearchValueListHandler {
private Integer currentPage;
private List<EmployeeDto> searchResult = new ArrayList<EmployeeDto>();
private List<EmployeeDto> currentPageRecords = new ArrayList<EmployeeDto>();
private Integer firstPageNbr;
private Integer lastPageNbr;
private final Integer MAX_RECORDS_PERPAGE=20;
private final Integer MAX_PAGELINKS=10;
private boolean isNextClicked=false;
private boolean isPreviousClicked=false;
private Map searchParams=new HashMap();
public void reset(){
// set default value to properties
}
// set this value when the user click on the page nbr
public void setSelectedPage(Integer selectedPageNbr){
this.currentPage=selectedPageNbr;
setNextPageRecords();
}
public void setNextClicked(boolean isNextClicked){
this.isNextClicked=isNextClicked;
}
public void setPreviousClicked(boolean isPreviousClicked){
this.isPreviousClicked=isPreviousClicked;
}
private void setNextPageRecords() {
if (isNextClicked) {
// retrieve next set of records from database by passing searchParams and addAll rows to searchResult
firstPageNbr=currentPage+1;
lastPageNbr=firstPageNbr+searchResult.size()/MAX_PAGELINKS;
if(searchResult.size()%MAX_PAGELINKS>0){
lastPageNbr++;
}
}
}
public List<EmployeeDto> getCurrentPageRecords(){
currentPageRecords.clear();
for(int count=1;count<=MAX_RECORDS_PERPAGE && (currentPage*MAX_RECORDS_PERPAGE+count)<searchResult.size();count++){
currentPageRecords.add(searchResult.get(count));
}
return currentPageRecords;
}
}

Save the instance of EmployeeSearchValueListHandler in session scope and reuse the same. Remove this object from session when the user navigates to other page.

Category: Java  | One Comment
Author:
Thursday, March 24th, 2011

Following is the code for sorting two dimensional array by given key.

<?php
$arr = array();
$arr[0]['id'] = 1;
$arr[0]['name'] = 'sathish';
$arr[0]['role'] = 1000;
$arr[1]['id'] = 2;
$arr[1]['name'] = 'siyam';
$arr[1]['role'] = 200;
$arr[2]['id'] = 3;
$arr[2]['name'] = 'prabhu';
$arr[2]['role'] = 1234;
$arr[3]['id'] = 4;
$arr[3]['name'] = 'hawai';
$arr[3]['role'] = 111;
$arr[4]['id'] = 5;
$arr[4]['name'] = 'dean';
$arr[4]['role'] = 999;
$result = sortTwoDimensionArrayByKey($arr,'name');
echo "<pre>";
print_r($result);
echo "</pre>";
function sortTwoDimensionArrayByKey($arr, $arrKey, $sortOrder=SORT_ASC){
foreach ($arr as $key => $row){
$key_arr[$key] = $row[$arrKey];
}
array_multisort($key_arr, $sortOrder, $arr);
return $arr;
}
?>

This will output:

Array
(
[0] => Array
(
[id] => 5
[name] => dean
[role] => 999
)
[1] => Array
(
[id] => 4
[name] => hawai
[role] => 111
)
[2] => Array
(
[id] => 3
[name] => prabhu
[role] => 1234
)
[3] => Array
(
[id] => 1
[name] => sathish
[role] => 1000
)
[4] => Array
(
[id] => 2
[name] => siyam
[role] => 200
)
)

Category: PHP | Tags: ,  | 2 Comments
Author:
Thursday, March 24th, 2011

We have given a feature of Export to Excel in our project, for which we have used PHPExcel package. PHPExcel is used to create excel documents dynamically using PHP programming language.

We come across a cool feature called “Grouping”, which adds “+/-“ icons to expand or collapse the rows or colums.

Attached the screenshot.

excel1

It shows the rows in collapse mode
excel2

Shows the rows in expanded mode.

It’s very easy to implement this feature using PHPExcel.

Code to add collapse feature to rows

$objPHPExcel->getActiveSheet()->getRowDimension(1)->setOutlineLevel(1);
$objPHPExcel->getActiveSheet()->getRowDimension(1)->setVisible(false);
$objPHPExcel->getActiveSheet()->getRowDimension(1)->setCollapsed(true);

The above code hides the Row 1 and add the icon buttons at the top which helps to collapse / expand all.

Code to add collapse feature to columns

$objPHPExcel->getActiveSheet()->getColumnDimension (‘A’)->setOutlineLevel(1);
$objPHPExcel->getActiveSheet()->getColumnDimension (‘A’)->setVisible(false);
$objPHPExcel->getActiveSheet()->getColumnDimension (‘A’)->setCollapsed(true);

Attached the Excel sheet generated using PHPExcel

Excel File

Author:
Thursday, March 24th, 2011

Namespaces were introduced in php 5.3 .It will solve the conflict arising due to classes having same name . Suppose you have a huge application and you have many classes and function . One of the classes which is existing in the application is User class which handles all user related queries. Now you have a requirement of integrating a third party plugin /api into your application and in this plugin you have the class name User. Now there is a conflict between between two classes . One is your applications User class and other is the third party api User class. So to resolve this scenario Zend came up with a concept of Namespaces . This is only available in php>= 5.3

In other word we can say that namespaces allow the us to seperate code into modules or groups which in turn makes the code easier to read.

To declare a namespace we have to type namespace followed by the name of the namespace .
Eg:namespace myappuser

We can also specify the sub namespaces by using backslashes(\). It is a best practice to specify the name spaces same a s the directory path.

In library/userClass.php we can declare a namespace myuserlib and we write a class myUser. In Index.php we need to include the class and instantiate it . Since we have defined myUser is in the namespace myuserlib we must refer the class as myuserlib \myUser. We can also use the use keyword . We need to specify which namespace you are using at the top of the file .

/library/userClass.php
namspace myuserlib;
class myUser
{
public function userName()
{
echo ‘Jack’;
}
}

In index.php:

require 'library/ userClass.php';
//This will display Error, Class not found.
$myuser = new myUser ();
//This will Display Jack on the screen.
$ myuser = new myuserlib \myUser();
$ myuser ->userName();

//This will display Jack on the screen

use myuserlib \myUser;
$ myuser = new myUser ();
$ myuser -> userName ();

//This will display Jack

use myuserlib \ myUser as newUsername;
$username = new newUsername ();
$ username -> userName ();

Category: General, PHP  | Leave a Comment