Tagged: PHP RSS Toggle Comment Threads | Keyboard Shortcuts

  • softwareandme 1:11 pm on September 25, 2010 Permalink
    Tags: design patterns, object oriented, PHP,   

    Php object oriented programming with design patterns 

    There are some certain designs in software development like in designing an aircraft. While designing an aircraft designers use some patterns, for example there is a pattern for landing gears. They are located under the aircraft and they have supports which are joint to the fuselage. Designer does not have to design a landing gear from scratch, if it is not needed, because he knows what is the pattern of a landing gear. Patterns are like templates while designing and building an automobile or aircraft.

    Software developers also need patterns for building their software projects like in other engineering disciplines. People say that Php is not suitable for object oriented programming in their blogs, it is not true! Php gives you chance to develop in procedural concept or in oop concept. Sometimes you need procedural programming though (but dont use procedural programming a lot in your oop projects it will turn your code to spaghetti code, just use where you have to use procedural programming). I used java which is known as the most suitable programming language for oop, but when you see  a Main function to run your program people who say php is not a suitable language for oop may think about this about other oop languages like java,c++. This is not true again all of these languages try to make their job, there is not a better or worse programming language. There are programming languages which are suitable for your needs and which are not suitable.

    I use object oriented programming in my projects with design patterns they help you to solve some problems in an efficient and fast way.

    In php.net site we see some patterns like factory and singleton design patterns, this is really cool, just look at the code dont try to understand if you do not know abything about design pattern i will explain what are design patterns and when we should use them.

    class Example
    {
        // The parameterized factory method
        public static function factory($type)
        {
            if (include_once 'Drivers/' . $type . '.php') {
                $classname = 'Driver_' . $type;
                return new $classname;
            } else {
                throw new Exception('Driver not found');
            }
        }
    }
    

     
  • softwareandme 10:00 pm on April 21, 2010 Permalink
    Tags: PHP   

    Php Operators (3) 

    Php operators are grouped in some sections, we gave the common operators in our previous article;

    • Assignment
    • Arithmetic
    • Comparison
    • Logical
    • String
    • Bitwise
    • Error control
    • Execution
    • Incrementing / decrementing
    • Array
    • Type

    What is an operator?
    If you want to change a variables value, multiply two numbers, compare two variables you use operators. Operators do operations on variables and sometimes you use them in your functions also.

    Assignment Operators
    They set the left operands value from its right. If you assign a value to a varible you use = (equals) operator. $variable = 1453; It means assign 1453 to variable.

    Arithmetic Operators
    They are used for arithmetic operations like adding,subtracting,modulus and multiplying.

    -$a Negation Opposite of $a.
    $a + $b Addition Sum of $a
    and $b.
    $a – $b Subtraction Difference of $a and $b.
    $a * $b Multiplication Product of $a and $b.
    $a / $b Division Quotient of $a and $b.
    $a % $b Modulus Remainder of $a divided by $b.

    $variable = (((3+7)*9+9)*10)%10;
    

    $variable’s value is 0
    $variable = 97%7;
    

    $variable is 6

    Comparison Operators
    Used for comparing two values, they do not assign anything just compare the values. You may use comparison operators on different types of variables, like comparing string and integer variables, since php is a loosely typed language php does not give you any error, but you should be careful about comparing two variables. If you just want to check if a variable has “FALSE” boolean value you may try to use ($c == false), but  if $c is 0 then comparison will be true but that s not what you expect! Ok, no problem php has a solution for this you may always try === for checking for variable type and value. Comparison operators are used everywhere in your code, if you are new to programming just learn them very well.

    $a == $b Equal TRUE if $a is equal to $b.
    $a === $b Identical TRUE if $a is equal to $b, and they are of the same type. (introduced in PHP 4)
    $a != $b Not equal TRUE if $a is not equal to $b.
    $a <> $b Not equal TRUE if $a is not equal to $b.
    $a !== $b Not identical TRUE if $a is not equal to $b, or they are not of the same type. (introduced in PHP 4)
    $a < $b Less than TRUE if $a is strictly less than $b.
    $a > $b Greater than TRUE if $a is strictly greater than $b.
    $a <= $b Less than or equal to TRUE if $a is less than or equal to $b.
    $a >= $b Greater than or equal to TRUE if $a is greater than or equal to $b.

    Logical Operators
    We use them for logical operations like xor,and, not,or, they return boolean values

    $a and $b And TRUE if both $a and $b are TRUE.
    $a or $b Or TRUE if either $a or $b is TRUE.
    $a xor $b Xor TRUE if either $a or $b is TRUE, but not both.
    ! $a Not TRUE if $a is not TRUE.
    $a && $b And TRUE if both $a and $b are TRUE.
    $a || $b Or TRUE if either $a or $b is TRUE.

    String Operators
    Php has two string operators one of them is string concatenation operator and the other one is concatenating assignment operator.
    String concatenating operator is . , and used for concatenating two strings.

    $string_me    = 'Izmir';
    $string          = 'Istanbul';
    $string_new   = 'Eskisehir';
    $string_concat = $string_me.$string.$string_new; //</strong>concats,adds, strings to each other $string_concat is 'IzmirIstanbulEskisehir'
    

    String concatenating assignment operator is .= , it appends argument on the right to the argument left.

    $string = 'C++'; //$string value is 'C++'
    $string .= ' PHP'; // PHP is appended to $string , new value of the $string is 'C++ PHP'
    

    Bitwise operators
    Bitwise operators are used to evaluate and manipulate of specific bits within an integer. Multiplying by two and dividing by two can be made by bit shifting in Php with bitwise operators.

    $a & $b And Bits that are set in both $a and $b are set.
    $a | $b Or (inclusive or) Bits that are set in either $a or $b are set.
    $a ^ $b Xor (exclusive or) Bits that are set in $a or $b but not both are set.
    ~ $a Not Bits that are set in $a are not set, and vice versa.
    $a << $b Shift left Shift the bits of $a $b steps to the left (each step means “multiply by two”)
    $a >> $b Shift right Shift the bits of $a $b steps to the right (each step means “divide by two”)

    Error Control Operators

    @ is the php error control operator which is used to ignore any error messages in expressions. If it is used in an expression (we put it inf front of expressions) error messages caused by expression will not be showed. I dont suggest this operator, dont try to use it. Dont try to hide errors or notices with @ operator. Try to solve your problems and then use error_reporting function or php.ini file to set your error reporting level.

    $variable = @$_SESSION[$key]; //will not show you a notice if the index $key does not exist
    

    Execution operators

    Php uses backticks “ as execution operators, you may run any command by using execution operators. It is dangerous to use backticks to run commands on your system, be careful about backticks.

    $showme = `ls /var/www`;
    echo $showme;
    

    Incrementing / decrementing operators

    ++$a Pre-increment Increments $a by one, then returns $a.
    $a++ Post-increment Returns $a, then increments $a by one.
    –$a Pre-decrement Decrements $a by one, then returns $a.
    $a– Post-decrement Returns $a, then decrements $a by one.

    Array operators

    $a + $b Union Union of $a and $b.
    $a == $b Equality TRUE if $a and $b have the same key/value pairs.
    $a === $b Identity TRUE if $a and $b have the same key/value pairs in the same order and of the same types.
    $a != $b Inequality TRUE if $a is not equal to $b.
    $a <> $b Inequality TRUE if $a is not equal to $b.
    $a !== $b Non-identity TRUE if $a is not identical to $b.

    Type operators
    İnstance of is used as type operator, if we want to know if an object is instantiated from a certain class we use instanceof.

    class Aircraft
    {
    }
    class Airbus extends Aircraft
    {
    }
    
    class Boeing extends Aircraft
    {
    }
    
    $airbus = new Airbus();
    $boeing = new Boeing();
    
    if($airbus instanceof Airbus)
    {
            echo "airbus object is instance of the Airbus class\n";
    }
    else
    {
            echo "airbus object is not instance of Airbus class";
    }
    
    if($boeing instanceof Airbus)
    {
            echo "boeing object is instance of Airbus class";
    }
    else
    {
            echo "boeing object is not instance of Airbus class\n";
    }
    

    Output:
    airbus object is instance of the Airbus class
    boeing object is not instance of Airbus class

    Php has three types of operators

    • Unary operators : They operate on one value, like !,++,–
    • Binary operators : They operate on two value, like assignment, increment and assignment, comparison, multiplying
    • Tertiary operator : ?: It is used for comparison, it is used like in here ( $compare_me == $compare_me_second ) ? $we_are_same : $no_we_are_not_same; If $compare_me and $compare_me_second are same it returns $compare_me
     
  • softwareandme 9:24 pm on April 21, 2010 Permalink
    Tags: PHP, php syntax, , software development   

    Php Syntax And Variables (2) 

    Hi,

    We are going to learn php syntax and variables on this article.

    We have talked about php syntax on the first php article, the syntax looks like c,c++,java and if you know one of these languages’ syntax it will be easy to learn php syntax.

    Php is a scripting language and we must say to its interpreter where the php code begins and where it ends. We use to tell the php interpreter it is a php script and it should interprets the script among these tags.

    <?php
    // What are these slashes?
    //Php script ends here
    ?>
    

    //: Double slashes means this line will not be interpreted by the interpreter, this line wont run , it is used for comment lines. Comment lines may be used to add extra information about the code, adding todo item, informing your colleagues about the code, etc.

    Before starting php syntax again we should look at what are variables and how can we define them. Variable stores data in it, variable name is a symbolic name associated with a value. Php has different variable types but php dont use them to define variables’ types. Php knows type of variable according to its value.If you assign a string to a variable then you may assign an integer and again you may assign an object to the variable.

    If you try to do this on C++ you have to use type casting. Php is a loosely typed language because of this feature.

    <?
    $string = 'Hello world!'; //String variable
    $string = 7; //Integer
    $string = 7.3; //Floating number , Float
    $string = new Object(); // Object
    ?>
    

    Php variables have $ sign in front of them. The second character of the variable i mean the character after $ sign must be a letter or underscore. Variable stores data so we should know how to assign data to a variable, we assign data to a variable by = (equals) sign. Equals assigns from right to the left, what does it mean? It means = (equals) gets the value from its right and puts it into its left. Php uses ; sign to assign values,references to variables, run functions.

    Php uses { } bracets for code blocks, code block is a piece of code which does something (multiply two numbers, checking if user has logged in etc), we write code inside { and } tags in code blocks. Code blocks are used in comparisons, functions, class methods, class declarations.

    In programming languages there are operators for making some processes on variables,functions,objects, like multiplying two numbers, assigning an object as a reference, comparing two strings etc. The next article describes php operators so please try to understand the operators which are located below;

    Arithmetic Operators

    Operator Description Example Result
    + Addition x=2
    x+2
    4
    - Subtraction x=2
    6-x
    4
    * Multiplication x=4
    x*3
    12
    / Division 8/2
    16/4
    4
    4
    % Modulus (division remainder) 7%2
    10%8
    10%2
    1
    2
    0
    ++ Increment x=7
    x++
    x=8
    Decrement x=7
    x–
    x=6

    Assignment Operators

    Operator Example Is The Same As
    = x=y x=y
    += x+=y x=x+y
    -= x-=y x=x-y
    *= x*=y x=x*y
    /= x/=y x=x/y
    .= x.=y x=x.y
    %= x%=y x=x%y

    Comparison Operators

    Operator Description Example
    == is equal to 4==8 returns false
    != is not equal 4!=8 returns true
    <> is not equal 4<>8 returns true
    > is greater than 4>8 returns false
    < is less than 4<8 returns true
    >= is greater than or equal to 4>=8 returns false
    <= is less than or equal to 4<=8 returns true

    Logical Operators

    Operator Description Example
    && and x=6
    y=3

    (x < 10 && y > 1) returns true

    || or x=6
    y=3

    (x==4 || y==4) returns false

    ! not x=6
    y=3

    !(x==y) returns true

    There are also different operators in php we try to explain them in our next article.

     
  • softwareandme 6:42 am on October 1, 2009 Permalink
    Tags: cleanurl, , PHP, smarty   

    Smarty Cleanurl plugin 

    I developed a cleanurl which makes it easy to switch between classic urls and clean urls like ( http:/www.site.com/instrument/view/1 for http://www.site.com/?component=instrument&action=view&id=1 )

    before adding the component you should make some changes like in .htaccess and Smarty.class.php

    in Smarty.class.php add this line ( by default it is false )

    Code:
    /**

    • When set, smarty cleanurls are enabled
    • @var boolean

    */
    var $cleanurl = false;

    among the class attributes, i use it integrated with smarty and when i want to enable cleanurls i just tell to smarty to set this value true

    Code:
    $smarty = new Smarty();
    //
    //smarty initialization by you like template_dir etc
    //
    $smarty->cleanurl = true;

    you can use another method to enable cleanurls but for now it works like this.

    then you should change your .htaccess according to your urls, for example we should write a .htaccess for above url example

    Code:
    # this is the initialization
    Options +FollowSymLinks
    RewriteEngine On
    RewriteBase /alem/alem/
    # these are the rewrite conditions
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    # and finally, the rewrite rules
    RewriteRule ^([a-zA-Z0-9\-]+)/?$ index.php?component=$1 [L,QSA]
    RewriteRule ^([a-zA-Z0-9\-]+)/([a-zA-Z0-9\-]+)/?$ index.php?component=$1&action=$2 [L,QSA]
    #id is is an integer
    RewriteRule ^([a-zA-Z0-9\-]+)/([a-zA-Z0-9\-]+)/([0-9\-]+)/?$ index.php?component=$1&action=$2&id=$3 [L,QSA]

    the last line of this .htaccess sample makes your urls clean. You should change the .htaccess according to your url structure.

    And the plugin itself should be added under the plugins directory.

    Then all you have to do is just putting your urls as normal urls in cleanurl’s url attribute like this one

    Code:
    {cleanurl url="?component=instrument&action=instrument&id=1" name="I am a Link"}

    it will give this output when cleanurls are not enabled

    Code:
    I am a Link

    and this one when cleanurls are enabled

    Code:
    I am a Link

    url and name attributes are required and there are other attributes like;

    title : when title attribute is set it adds a title to your link e.g.<a title="TITLE", if you dont set the title name attribute will be shown as the title

    extension: if you add and extension to your clean urls like instrument/view/1.html you should set this value as {cleanurl extension=”.html” ….. }

    image: if you want to give link to an image you should set the image attribute and it will have a link and with image_class attribute you can give a class for your image

    When using with lists you should use active and id lets explain it with an example if you have a list like this, before this

    $active should be assigned with smarty assign or you can just use $smarty.get.action for active attribute, for this example in php you should do this

    Code:
    $action = isset($_GET['action']) ? $_GET['action'] : '';
    $smarty->assign('action',$action);
    
    Code:
    • {cleanurl url=""?component=instrument&action=view&id=1" name="Link 1" id="view" active="$action"}
    • {cleanurl url=""?component=instrument&action=review&id=1" name="Link 2" id="review" active="$action"}
    • {cleanurl url=""?component=instrument&action=order&id=1" name="Link 3" id="order" active="$action"}
    • {cleanurl url=""?component=instrument&action=list" name="Link 4" id="list" active="$action"}

    when the assigned value for id and active matches, the cleanurl will not show a link it will show only the text inside a span

    if you want to use this for a horizontal list also you can try this css

    Code:
    .horizontal_list { list-style-type: none; padding: 0; margin: 0; }
    .horizontal_list li { display: inline; }
    .horizontal_list li a { padding-left: 7px; }
    .horizontal_list li span { font-weight: bold; color: #3B5998; padding-left: 7px; }
    

    and here is the code, and one thing to add i always use base href in my sites if you dont use it you may want to change the plugin and add the base_url in front of the cleanurl, that s up to you.

    I hope it helps,

    just copy the below code and save it and copy the saved file under smarty plugins fodler, function.cleanurl.php

    Code:
    <?php
    /**
    * Smarty plugin
    * @package Smarty
    * @subpackage plugins
    */
    </code><code>
    /**
    * Smarty {cleanurl} function plugin
    *
    * Type:     function<br>
    * Name:     cleanurl<br>
    * Date:     July 1, 2009<br>
    * Purpose:  Cleans the urls to make them search-engine-friendly<br>
    * Input:<br>
    *         - url    = url for cleaning
    *          - name   = name for link
    *          - title   = title for link
    *
    * Examples: {cleanurl url="http://cleanurl.com/?sec=software&com=firma&act=info&id=1" name="Clean"}
    * Output:   http://cleanurl.com/software/firma/info/1
    * @link http://smarty.php.net/manual/en/language.function.cleanurl.php {cleanurl}
    *      (Smarty online manual)
    * @author   Onur GUZEL onur.oguzel[at]gmail.com
    * @version  0.1
    * @param array
    * @param Smarty
    * @return string
    */
    function smarty_function_cleanurl($params, &$smarty) {
    foreach ( $params as $_key => $_val ) {
    switch ($_key) {
    case 'url':
    case 'name':
    case 'title':
    case 'extension':
    case 'image':
    case 'image_class':
    case 'active':
    case 'id':
    case 'askmessage':
    $$_key = (string)$_val ;
    break;
    default :
    $smarty->trigger_error ( "cleanurl:  no permission to add extra attribute '$_key'", E_USER_NOTICE );
    break;
    }
    }
    
    if (empty ( $url )) {
    $smarty->trigger_error ( "cleanurl: missing 'url' parameter", E_USER_NOTICE );
    return;
    }
    if (empty ( $name )) {
    $smarty->trigger_error ( "cleanurl: missing 'name' parameter", E_USER_NOTICE );
    return;
    }
    
    if( empty($title) )
    {
    $title = $name;
    }
    
    $urls = explode('&amp;',$url);
    $urlstring = '';
    if( sizeof($urls) )
    {
    $j=0;
    foreach( $urls as $url_ )
    {
    $url_tmp = explode('=',$url_);
    $urlstring .= $url_tmp[1];
    if($j!=sizeof($urls)-1) $urlstring .= '/';
    $j++;
    }
    }
    else
    {
    $smarty->trigger_error ( "cleanurl: please check the url attribute", E_USER_NOTICE );
    }
    
    if( isset($extension) )
    {
    $urlstring .= $extension;
    }
    $stringurl = '';
    
    $image_src = '';
    if( count($image) )
    {
    $image_src = '<img src="'.$image.'" border="0" alt="'.$name.'" title="'.$title.'"/>';
    $name = $image_src;
    }
    
    if( $smarty->cleanurl )
    {
    $stringurl = '<a href="'.$urlstring.'" title="'.$title.'">'.$name.'</a>';
    }
    else
    {
    $stringurl = '<a href="'.$url.'" title="'.$title.'">'.$name.'</a>' ;
    }
    
    if( isset($active) && isset($id) && $active == $id ) $stringurl = '<span title="'.$title.'">'.$name.'</span>';
    
    return $stringurl;
    }
    
    ?>

    Regards

     
  • softwareandme 5:19 am on October 1, 2009 Permalink
    Tags: , introduction, PHP,   

    php, How I met and decided to use again 

    First i heard about php in a computer magazine, when i was in high school. After that I met apache and their good friend mysql came to meeting.  Then in the university years, the good friend Slackware joined us. It was fun to code with php and python while trying to learn c. They were easy and clean languages,  php syntax was so similar to c and then i decided to use php on the web projects, c was not something i was looking for i met c++ then oop adventure started. I had some ideals and tried to develop a project for my license thesis, I used C++ in the project. It was an unsuccessfull project, so no need to mention it.

    I was a C++ programmer and learned and studied Object Oriented Programming concepts a lot more than the procedural concepts. I just used procedural concept while learining how to code in c then i used c++ and tried to learn it. I am not a C++ professional but i first met with C++ seven years ago, i developed some projects with c++ but i had to develop with java and c#. After learning c++, java was not so hard, and i have found an equatition for c#

    c# = (c+ – +) + (java)

    c# was a really easy and good language for a c++ and java programmer.

     I was coding with php for years, since high school days. Php was not an object oriented language I was not able to use classes ( i mean php 3). I was writing some basic codes with php. Some day i have seen that object oriented principles applied in php. When i was developing code with c#, php’s oop was getting more stable. I was a web developer who can code with c# , php and java using netbeans, visual studio and vim. I didnot develop big projects with netbeans or visual studio, I was developing some other coders’, who left the work, libraries.

    Java and C# did not have clean code for me and developer was not free. Performance issues were making me so mad. Netbeans/Java or Eclipse/Java is more free than VS/C#. I returned to old friend php and realized that developers really did a good work and add the oop in php in a good manner. Php has still some problems like memory management but who doesn’t ?( c# or java :)   )

    Php and c integration always makes you feel good, you know c stands under the hood and you can add more cylinders and valves to the engine if you want to do that. Developers can develop php modules of their own if they need even they can change or add their rules to the language.

    Community support is really better than the other popular programming languages and python community is a good community like php community. There are a lot of magazines, books, professioanls, sites, irc channels, conferences, companies  about php.

    After php 5 and oop, php started to run ( it was walking )  and then we have seen some scalable huge projects writtien in php. sunn’s and ms’s stories about scalability were not right about their development environments and frameworks. Good software engineers told and show ( sunn and ms and the other big lier companies ) them developing scalable and good program is not something related to the language you use, it is something related to your software design and engineering. Design comes with freedom, if someone or something is not free, design wont be there; obligations will take place instead of design and freedom. Linux also freed the php,apache and mysql and gave a good development environment to free developers. I am a really advocate for free software ( free is not related to money, it is the free in freedom ) and enjoy when i see a succesfull free software project.

    After I have finished military service and as a coincidence i found jobs related to php and meet with the oldfriend again, now as a professional i have been developing oop php for three years.

    Blogged with the Flock Browser
     
  • softwareandme 4:35 am on July 31, 2009 Permalink
    Tags: bug, locale, PHP   

    Php Turkish Locale Problem 

    There is a seven year old bug reported ( bug #18556) in php, when you set locale to turkish all of the class names in your code turns to lowercase, then probably your program will say i can not find class Init, because it tries to find the init class.

    Assigning all of the locale settings one by one is a good practice but there is easy solution for this problem.

    setlocale(LC_ALL, 'tr_TR'); causes the error
    //when you add and set LC_CTYPE to another locale 
    //this problem can be solved.
    setlocale(LC_CTYPE, 'en_US');
    find the init class
     
c
compose new post
j
next post/next comment
k
previous post/previous comment
r
reply
e
edit
o
show/hide comments
t
go to top
l
go to login
h
show/hide help
shift + esc
cancel
Follow

Get every new post delivered to your Inbox.