PHP – function use 

December 8th, 2012

As with the previous post about the use method within php (here), you are also able to use the use method attached to a callable function as in

function ($parameter) USE ($somevalue)

So you are able to use any variables that are within scope within the new function, below is an example where I am using the array walk methods callback (which means call a function that is available). The function is using the values within the array ($arrays 4 and 5) and adding them to the $value variable that is passed within the use parameters (here I am using the & symbol which means to pass in reference and not just a copy of the value (you are able to alter the actual parameter passed), so in this instance the $value starts of with 1, then adds 4 and then 5 to it which in turn the result is 10.

$value = 1;
$callback = function ($one) use (&$value) {
	$value += $one;
};
$arrays = array(4,5);
array_walk($arrays, $callback);
print_r("value : " .$value);

And the output would be.

value : 10

WFC Soap class within an class communicating with PHP 

August 4th, 2012

Within the Windows Foundation Classes you are able to create SOAP end points. These end points you are able to communicate using classes funny enough (because of the WFC being classes). But to communicate with these is fine with PHP and also when you sometimes have a class within an class as a parameter passing to the SOAP end point. Well you are able to do it within PHP as well.

If you have a WFC service and add these to the service for the ServiceContract and create the DataContract’s and DataMembers

[ServiceContract]
public interface IService1
{
    [OperationContract]
    string NewValue(NewName name);
}
 
[DataContract]
public class SecondName
{
    int svalue1;
    int svalue2;
 
    [DataMember]
    public int Svalue1
    {
        get { return svalue1; }
        set { svalue1 = value; }
    }
 
    [DataMember]
    public int Svalue2
    {
        get { return svalue2; }
        set { svalue2 = value; }
    }
}
 
[DataContract]
public class NewName
{
    SecondName secondValue = new SecondName();
 
    [DataMember]
    public SecondName SecondValue
    {
        get { return secondValue; }
        set { secondValue = value; }
    }
}

Created the SecondName class as the second named class with the svalue1/2 within in turn the NewName named class will reference the SecondName class.

And then within the class that implements the interface here is the function name to call within the soap end point called NewValue.

public string NewValue(NewName namesec)
{
    return string.Format("Value : {0}", namesec.SecondValue.Svalue1 + namesec.SecondValue.Svalue2);
}

Well to find out what you need to pass to the soap call I was using an WFC application to write out the debugging information with altering the web.config by

    <system.serviceModel>
      <diagnostics>
        <messageLogging
             logEntireMessage="true"
             logMalformedMessages="false"
             logMessagesAtServiceLevel="true"
             logMessagesAtTransportLevel="false"
             maxMessagesToLog="3000"
             maxSizeOfMessageToLog="2000"/>
      </diagnostics>
    </system.serviceModel>
  <system.diagnostics>
    <sources>
      <source name="System.ServiceModel.MessageLogging">
        <listeners>
          <add name="messages"
          type="System.Diagnostics.XmlWriterTraceListener"
          initializeData="c:\temp\messages.svclog" />
        </listeners>
      </source>
    </sources>
  </system.diagnostics>

which in turns creates a file and in that file there is xml definition what is being sent.

<s:Body>
 <NewValue xmlns="http://tempuri.org/">
 <name xmlns:d4p1="http://schemas.datacontract.org/2004/07/WcfService1" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
 <d4p1:SecondValue><d4p1:Svalue1>200</d4p1:Svalue1><d4p1:Svalue2>100</d4p1:Svalue2></d4p1:SecondValue>
 </name>
 </NewValue></s:Body>
</xml>

and within PHP you are able to copy this. but note that the parameter to send is “name” which is not the same as the parameter above (namesec) you have to send to “name” which is what the soap end point is looking for.

class SecondName {
    public $Svalue1;
    public $Svalue2;
}
 
class NewName {
    public $SecondValue;
 
    public function NewName($s1, $s2)
    {
        $this->SecondValue = new SecondName();
        $this->SecondValue->Svalue1 = $s1;
        $this->SecondValue->Svalue2 = $s2;
    }
}
 
$objN = new NewName(200,100);
 
//Create a SOAP client
$client = new SoapClient("http://192.168.0.3/Service1.svc?wsdl");
$retVal = $client->NewValue(array ("name" => $objN));
 
print_r($retVal->NewValueResult);

and the output is

Value : 300

Have attached a file of the project for the WFC webserver and also the php code.

PHP – Use 

July 11th, 2012

From a follow on from my previous post about namespace, when you want to use another name, shorter than the actual namespace of the namespace you are able to use “use”. Probably best to show in code

include "codingfriends.php";
 
use codingfriends as cf;
 
echo cf\sayHello()."<br/>";

the codingfriends.php file is

<?php
namespace codingfriends;
 
function sayHello()
{
    echo "Say hello from codingfriends.";    
}
 
function sayHelloFromSub()
{
    echo sub\sayHello();
}
?>

so that the “use” will alter the namespace of codingfriends to cf instead so that you are able to call codingfriends as cf, so when

echo cf\sayHello()."<br/>";

is called it will call the codingfriends\sayHello() function.

PHP – namespace 

July 10th, 2012

Namespace‘ing is a great way of splitting functions / classes into different spaces that could have the same name but do not cause issues. This is great if you are trying to combine different projects together that many have the same function names and you want to call different projects code functions without having to worry that you are calling the wrong function.

For example if you have a file called codingfriends.php

<?php
namespace codingfriends;
 
function sayHello()
{
    echo "Say hello from codingfriends.";    
}
 
function sayHelloFromSub()
{
    echo sub\sayHello();
}
?>

and another file called codingfriendssub.php

<?php
namespace codingfriends\sub;
 
function sayHello()
{
    echo "Say hello from codingfriends sub module";    
}
?>

and then have the index.php file

 
<?
include "codingfriends.php";
include "codingfriends.sub.php";
 
echo codingfriends\sayHello()."<br/>"; // calling the codingfriends namespace
echo codingfriends\sub\sayHello()."<br/>"; // call the codingfriends sub namespace
echo codingfriends\sayHelloFromSub()."<br/>"; // calling the sub namespace quicker.
?>

then the first two lines include the two different name spaces and you are able to call the same function names without having to worry that you are calling the wrong function.

echo codingfriends\sayHello()."<br/>"; // calling the codingfriends namespace

will call the sayHello() from within the namespace codingfriends

echo codingfriends\sub\sayHello()."<br/>"; // call the codingfriends sub namespace

will call the namespace codingfriendssub sayHello function and the best thing is is if you are within a namespace and want to call a sub namespace within your namespace (it is like a tree with roots) you are able to do

    echo sub\sayHello();

from within the namespace codingfriends, it will find the codingfriends\sub namespace and then call the sayHello() function within that namespace.

The output would be for the index.php file

Say hello from codingfriends.
Say hello from codingfriends sub module
Say hello from codingfriends sub module

Good courses 

July 10th, 2012

After some looking around, I have found some really good courses that show good coding standards and also allowed to be viewed online even if you are not paying.

David J. Malan, is a very good instructor and one of his courses

Google python code, string2.py 

December 4th, 2011

As from the previous post, I am doing the google’s python class code and if any one comes up different solutions to the googles version or mine, please post. So here is the string2.py solutions from me.

Verbing, needs to check for string over 3 and then only compare the last 3 characters for ‘ing’

# D. verbing
# Given a string, if its length is at least 3,
# add 'ing' to its end.
# Unless it already ends in 'ing', in which case
# add 'ly' instead.
# If the string length is less than 3, leave it unchanged.
# Return the resulting string.
def verbing(s):
  # +++your code here+++
  if len(s) < 3:
     return s
  elif (s[-3:] =='ing'):
     return s + 'ly'
  else:
     return s + 'ing'

Not bad, find the ‘not’ and ‘bad’, if bad after not then replace.

# E. not_bad
# Given a string, find the first appearance of the
# substring 'not' and 'bad'. If the 'bad' follows
# the 'not', replace the whole 'not'...'bad' substring
# with 'good'.
# Return the resulting string.
# So 'This dinner is not that bad!' yields:
# This dinner is good!
def not_bad(s):
  # +++your code here+++
  notV = s.find('not')
  badV = s.find('bad')
  if (badV > notV):
     return s[:notV] + 'good' + s[(badV+3):]
  return s

Font back, here we needed the modulus function to find out the reminder of a division.

# F. front_back
# Consider dividing a string into two halves.
# If the length is even, the front and back halves are the same length.
# If the length is odd, we'll say that the extra char goes in the front half.
# e.g. 'abcde', the front half is 'abc', the back half 'de'.
# Given 2 strings, a and b, return a string of the form
#  a-front + b-front + a-back + b-back
def front_back(a, b):
  # +++your code here+++
  aV = len(a)/2+(len(a)%2)
  bV = len(b)/2+(len(b)%2)
  return a[:aV]+b[:bV]+a[aV:]+b[bV:]

Google python code 

December 4th, 2011

After been talking with some friends, they said about putting some of the google code from there classes online encase other people come up with any other versions. So from the first of the classes that they was talking about was Python , so here is my code for these, may be other people may be doing and come up with different code ?

For first string1.py test there is 4 functions that you have code up and in order from the source code.

Donut, as from the below you just need do a compare on the parameter in.

# A. donuts
# Given an int count of a number of donuts, return a string
# of the form 'Number of donuts: <count>', where <count> is the number
# passed in. However, if the count is 10 or more, then use the word 'many'
# instead of the actual count.
# So donuts(5) returns 'Number of donuts: 5'
# and donuts(23) returns 'Number of donuts: many'
def donuts(count):
  # +++your code here+++
  if count >= 10:
     return 'Number of donuts: many'
  return 'Number of donuts: ' + str(count)

Both end, it is string manipulation and returning part of the string if longer enough.

# B. both_ends
# Given a string s, return a string made of the first 2
# and the last 2 chars of the original string,
# so 'spring' yields 'spng'. However, if the string length
# is less than 2, return instead the empty string.
def both_ends(s):
  # +++your code here+++
  if len(s) < 2:
    return ''
  return s[:2] + s[-2:]

Fix start, replace the characters within the string with a * that the same as the first character, so just need to concatenate the first character with the rest of the characters with any replaced :)

# C. fix_start
# Given a string s, return a string
# where all occurences of its first char have
# been changed to '*', except do not change
# the first char itself.
# e.g. 'babble' yields 'ba**le'
# Assume that the string is length 1 or more.
# Hint: s.replace(stra, strb) returns a version of string s
# where all instances of stra have been replaced by strb.
def fix_start(s):
  # +++your code here+++
  return s[0] + s[1:].replace(s[0],'*')

Mix up, change the first 2 characters from the two parameters around.

# D. MixUp
# Given strings a and b, return a single string with a and b separated
# by a space '<a> <b>', except swap the first 2 chars of each string.
# e.g.
#   'mix', pod' -> 'pox mid'
#   'dog', 'dinner' -> 'dig donner'
# Assume a and b are length 2 or more.
def mix_up(a, b):
  # +++your code here+++
  return b[:2]+a[2:]+' '+a[:2]+b[2:]