PSR-0 Final Proposal

Somehow the PSR-0 Final Proposal disappeared from groups.google.com. I’m putting it here since no one seems to have been responsible enough to post it elsewhere.
The following describes the mandatory requirements that must be adhered to for autoloader interoperability.

Mandatory:

  • A fully-qualified namespace and class must have the following structure \\(\)*
  • Each namespace must have a top-level namespace (“Vendor Name”).
  • Each namespace can have as many sub-namespaces as it wishes.
  • Each namespace separator is converted to a DIRECTORY_SEPARATOR when loading from the file system.
  • Each “_” character in the CLASS NAME is converted to a DIRECTORY_SEPARATOR. The “_” character has no special meaning in the namespace.
  • The fully-qualified namespace and class is suffixed with “.php” when loading from the file system.
  • Alphabetic characters in vendor names, namespaces, and class names may be of any combination of lower case and upper case.

Examples:

\Doctrine\Common\IsolatedClassLoader => /path/to/project/lib/vendor/Doctrine/Common/IsolatedClassLoader.php

\Symfony\Core\Request => /path/to/project/lib/vendor/Symfony/Core/Request.php

\Zend\Acl => /path/to/project/lib/vendor/Zend/Acl.php

\Zend\Mail\Message => /path/to/project/lib/vendor/Zend/Mail/Message.php

Underscores in namespaces and class names:

\namespace\package\Class_Name => /path/to/project/lib/vendor/namespace/package/Class/Name.php

\namespace\package_name\Class_Name => /path/to/project/lib/vendor/namespace/package_name/Class/Name.php
The standards we set here should be the lowest common denominator for painless autoloader interoperability. You can test that you are following these standards by utilizing this sample SplClassLoader implementation which is able to load PHP 5.3 classes.

Example Implementation

Below is an example function to simply demonstrate how the above proposed standards are autoloaded.
<?php

function autoload($className)
{
$className = ltrim($className, '\\');
$fileName = '';
$namespace = '';
if ($lastNsPos = strripos($className, '\\')) {
$namespace = substr($className, 0, $lastNsPos);
$className = substr($className, $lastNsPos + 1);
$fileName = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
}
$fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';

require $fileName;
}

SplClassLoader Implementation

The following gist is a sample SplClassLoader implementation that can load your classes if you follow the autoloader interoperability standards proposed above. It is the current recommended way to load PHP 5.3 classes that follow these standards.

http://gist.github.com/221634

Determining Month to Date Sales in Dynamics GP 10 with Project Accounting

This was a tough one. I needed to find month to date sales in GP compiling Sales Orders and entries in Project Accounting. To complicated things a little more, I needed to use the Invoicing amount in Sales Orders if they’ve been fully invoiced and the Invoiced amount from Project Accounting when it is more than the total Fee Schedule.

The SQL gets a little messy so I’ve tried to add some comments to clarify exactly what I’m trying to do. The basic idea is that I’m getting the total sales order numbers and performing a UNION with the total Project Accounting numbers then summing them with an outer query. You can modify this to include previous months by changing any references to a date field from “DATEADD(mm, DATEDIFF(mm,0,getdate()), 0)” (meaning, the first day of the current month) to “DATEADD(mm, DATEDIFF(mm,0,getdate()) -1, 0)” (the first day of the previous month) or can change that -1 to a -2 to look 2 months back.

There are likely many better ways to get this done, but this has seemed to work well so far.

Let me know if you have any questions or comments.

SELECT SUM("total") as "MTD Sales" 

FROM (

	SELECT myMonth, myMonthNUm, SUM("Totals") as total
	FROM 

	-- Sales Orders Entered this month
	(
		SELECT 

		-- Name of Month
		DateName(month,CASE WHEN Sales."CREATED DATE" < Sales."Order Date"
			THEN Sales."Created Date"
			ELSE Sales."Order Date"
		END) as myMonth,

		-- Number of Month
		month(CASE WHEN Sales."CREATED DATE" < Sales."Order Date"
			THEN Sales."Created Date"
			ELSE Sales."Order Date"
		END
	) as myMonthNum,

	-- Here, we look to see if the SO has been invoiced. If it has, we use the invoice amount
	-- otherwise, we use the subtotal.
	CASE WHEN Sales."Sales Document Status" != 'Complete'
	THEN (Sales."Subtotal" - Sales."Trade Discount Amount")
	ELSE (SUM(ISNULL(INV1."Subtotal",0)) + SUM(ISNULL(WORK."Subtotal",0)) - SUM(ISNULL(INV1."TRDISAMT",0)) )
	END
	AS Totals

	FROM dbo.SalesTransactions Sales
	LEFT JOIN dbo.SOP30200 SO
		ON SALES."SOP Number" = SO."SOPNUMBE"
	LEFT JOIN dbo.SOP10100 WORK
		ON SALES."SOP Number" = WORK."ORIGNUMB"
	LEFT JOIN dbo.SOP30200 INV1
		ON SO."SOPNUMBE" = INV1."ORIGNUMB"

	-- Look at orders made this month using the earlier date between created and order date
	WHERE
	CASE WHEN Sales."CREATED DATE" < Sales."Order Date"
		THEN Sales."Created Date"
		ELSE Sales."Order Date"
	END <  DATEADD(mm, DATEDIFF(mm,0,getdate()) + 1, 0)
	AND CASE WHEN Sales."Created Date" < Sales."Order Date"
		THEN Sales."Created Date"
		ELSE Sales."Order Date"
	END
	>=  DATEADD(mm, DATEDIFF(mm,0,getdate()), 0)
	AND Sales."SOP Type" = 'Order'
	AND (INV1."BCHSOURC" IS NULL OR INV1."BCHSOURC" = 'Sales Entry')
	GROUP BY Sales."SOP Number", Sales."Subtotal", Sales."Customer Name", Sales."Sales Document Status", Sales."Trade Discount Amount",

	CASE WHEN Sales."CREATED DATE" < Sales."Order Date"
		THEN Sales."Created Date"
		ELSE Sales."Order Date"
	END

	) as T
	GROUP BY myMonth,mymonthnum

	-- Now we'll include contracts entered in project accounting
	UNION
	(
		SELECT  Datename(month,(T."SuperDate")) as myMonth, month(T."SuperDate") as myMonthNum,

		-- Just as in Sales Orders, we'll use the billed amount if it is higher than the original contract amount
		SUM(CASE
		WHEN T."Total" > ISNULL(B.Billing,0)
		THEN "Total"
		ELSE ISNULL(B.Billing,0)
		END
		)
		as Totals
		FROM
		(	-- Here, we're grabbing the "as sold" amounts from the contract fee schedule for each contract line item
			SELECT
			Glue."Contract ID",
			MIN(SuperGlue."PA Forecast Begin Date") as SuperDate,
			SUM(Fee."PAFeeAmount") as Total
			FROM dbo.PA02101 Fee
			LEFT JOIN dbo.PAProjects Glue
			ON Fee."PAPROJNUMBER" = Glue."Project Number"
			LEFT JOIN dbo.PAContracts SuperGlue
			ON Glue."Contract ID" = SuperGlue."Contract ID"
			WHERE "PA Forecast Begin Date" >=  DATEADD(mm, DATEDIFF(mm,0,getdate()), 0)
			AND "PA Forecast Begin Date" <  DATEADD(mm, DATEDIFF(mm,0,getdate()) + 1, 0)
			GROUP BY Glue."Contract ID"
		) as T
		LEFT JOIN
		(   -- Here, we're looking at our total billed amount
			SELECT  "PACONTNUMBER", SUM("PABillingAmount") as Billing
			FROM dbo.PA11500
			GROUP BY "PACONTNUMBER"
		) as B
		ON T."Contract ID" = B."PACONTNUMBER"
		GROUP BY  Datename(month,(T."SuperDate")), month(T."SuperDate")
	)
) as P
GROUP BY myMonth, myMonthNum
ORDER BY myMonthNum

Bill of Materials and Quantities in Dynamics GP 10

Here’s a SQL query that will allow you to see what components go into a given finished part number along with the available, on hand, allocated, and back ordered quantities.

This is useful if you have a rush job with not enough quantity available in GP and want to see what’s actually in house.

Just define @needed as how many items you’re trying to manufacture and set @item to the finished part number. You’ll also need to enter in your own location code in the left join for ItemQuantities. The “Assembly” column will let you know if the component is itself an assembly. When I make a report out of this in Business Intelligence Development Studio, I use this column to show or hide a symbol to navigate to this report with the part number of the component (pretty much “scoping in” to that part) to see if the material is available to make that.
DECLARE @needed as INT
DECLARE @item as char(20)

SET @needed = 1
SET @item = '115-0001'

SELECT
Item."Item Description",
Bill."FINISHED GOOD ITEM NUMBER",
Bill."Component",
(Bill."QTY" * @needed) as "QTY",
Item."QTY Available",
Item."QTY On Order",
Item."QTY On Hand",
Item."QTY Allocated",
CASE
WHEN Sub.SubParts IS NOT NULL
THEN 1
ELSE 0
END as "Assembly"
FROM dbo.BillofMaterials as Bill
LEFT JOIN dbo.ItemQuantities as Item ON Bill."Component" = Item."Item Number" AND Item."Location Code" = 'YOUR LOCATION CODE'
LEFT JOIN
(
SELECT "Finished Good Item Number", COUNT(*) as SubParts FROM dbo.BillofMaterials
GROUP BY "Finished Good Item Number") as Sub
ON
Sub."Finished Good Item Number" = Bill."Component"

WHERE Bill."FINISHED GOOD ITEM NUMBER" = @item

Looking at Manufacturing Orders Associated with Sales Order Lines in Dynamics GP 10

Here’s a query that will allow you to see which Open SO Lines have MOs associated with them and which MO exactly it is.

This is helpful when you’re looking to find “lost orders” that haven’t yet been processed in Manufacturing.

SELECT 
MO."MANUFACTUREORDER_I",
Sales."SOP Number",
Sales."Item Number",
Sales."Order Date",
Sales."QTY",
Sales."QTY Remaining",
Sales."Customer Name",
Sales."Item Description",
Sales."Due Date"
FROM dbo.SalesLineItems Sales
LEFT JOIN dbo.SOP10202ON Sales."SOP Number" = dbo.SOP10202.SOPNUMBEAND Sales."Line Item Sequence" = dbo.SOP10202.LNITMSEQ
LEFT JOIN dbo.IS010001 As MOON Sales."SOP Number" = MO.SOPNUMBEAND Sales."Line Item Sequence" = MO.LNITMSEQAND Sales."Item Number" = MO.ITEMNMBR
WHERE Sales."SOP Type" = 'Order' AND Sales."Sales Document Status" != 'Complete'AND Sales."QTY Remaining" > 0
ORDER BY "SOP Number" ASC

Zend_Form_Element_Daterange with jQuery UI datepicker

It’s pretty easy to create a wrapper around Zend_Form_Element_Text to make a datepicker, but creating a good, smart daterange picker is a little more tricky.

The only two requirements are jQuery UI and that you have some way of injecting JavaScript into your site layout (I use a $this->layout()->headJavascript).

Other than that, this should be pretty plug-and-play.

Here are the 3x files you’ll need:
1. Your view script for the actual element (check in here for how I’m dealing with the JavaScript):
/application/views/scripts/misc/form/element/daterange.phtml

2. The actual element
/library/M/Form/Element/Daterange.php

3. And a filter to parse out the actual daterange when you do $form->getValues():
/library/M/Filter/Daterange.php

Have fun!

/library/M/Form/Element/Daterange.php
<?php

class M_Form_Element_Daterange extends Zend_Form_Element_Select {
public function init() {

$this->setDecorators(array(array('ViewScript', array(
'viewScript' => 'misc/form/element/daterange.phtml',
'viewModule' => 'default',
'class' => 'form element'
))));

return parent::init();
}
}

/library/M/Filter/Daterange.php

<?php

class M_Filter_Daterange implements Zend_Filter_Interface {

private $_param = null;

public function __construct($param, $options = array()) {
if (!is_string($param) || strlen($param) < 1) {
throw new Zend_Filter_Exception("param must be a string, and must have a length");
}
$this->_param = $param;
}

/**
* (non-PHPdoc)
* @see Zend_Filter_Interface::filter()
*/
public function filter($val) {
if ($val != 'custom') {
$rangestring = self::stringToRange($val);
if ($rangestring) {
return $rangestring;
}
}
if ($this->_param === null) {
throw new Zend_Filter_Exception("Must instantiate this class and pass a valid parameter");
}
$range = Zend_Controller_Front::getInstance()->getRequest()->getParam($this->_param, false);
$start = strtotime(Zend_Controller_Front::getInstance()->getRequest()->getParam($this->_param . '_start', false));
$end = strtotime(Zend_Controller_Front::getInstance()->getRequest()->getParam($this->_param . '_end', false));

if (!$start || !$end) {
return false;
}
return array(
'start' => date('Y-m-d', $start),
'end' => date('Y-m-d', $end),
);

}

/**
* Converts a known relative date range string to an array of dates, returns false on failure
*
* @param string $datestring
* @return array|bool
*/
static public function stringToRange($datestring) {
switch ($datestring) {
case 'yesterday':
$daterange = array(
'start' => date('Y-m-d', strtotime('yesterday')),
'end' => date('Y-m-d'),
);
break;
case 'weektodate':
$daterange = array(
'start' => date('Y-m-d', strtotime('sunday this week')),
'end' => date('Y-m-d'),
);
break;
case 'lastweek':
$daterange = array(
'start' => date('Y-m-d', strtotime('sunday last week')),
'end' => date('Y-m-d', strtotime('saturday -2 weeks')),
);
break;
case 'monthtodate':
$daterange = array(
'start' => date('Y-m-d', strtotime('first day of this month')),
'end' => date('Y-m-d'),
);
break;
case 'lastmonth':
$daterange = array(
'start' => date('Y-m-d', strtotime('first day of last month')),
'end' => date('Y-m-d', strtotime('last day of last month')),
);
break;
case 'yeartodate':
$daterange = array(
'start' => date('Y-m-d', strtotime('first day of this year')),
'end' => date('Y-m-d'),
);
break;
case 'lastyear':
$daterange = array(
'start' => date('Y-m-d', strtotime('first day of last year')),
'end' => date('Y-m-d', strtotime('last day of last year')),
);
break;
case 'all':
$daterange = array(
'start' => date('Y-m-d', strtotime('1970-01-01')),
'end' => date('Y-m-d'),
);
break;
default:
return false;

}
return $daterange;
}

}

/application/views/scripts/misc/form/element/daterange.phtml

<?php
/**
* Output a daterange element
*
*/

/**
* @var Zend_Form_Element
*/
$element = $this->element;
$opts = $element->getDecorator('ViewScript')->getOptions();

ob_start();
?>
<script>
$(document).ready(function() {
var dates = $(<?=json_encode('#' . $element->getName() . '_start, #' . $element->getName() . '_end')?>).datepicker({
changeMonth : true
, onSelect : function( selectedDate ) {
// don't let end date be after start date
var option = this.id == <?=json_encode($element->getName() . '_start')?> ? "minDate" : "maxDate",
instance = $(this).data("datepicker"),
date = $.datepicker.parseDate(
instance.settings.dateFormat || $.datepicker._defaults.dateFormat
, selectedDate
, instance.settings
);
dates.not(this).datepicker("option", option, date);
}

});

$(<?=json_encode('#' . $element->getName())?>).change(function() {
if ($(this).val() == 'custom') {
$(<?=json_encode('#_custom_daterange_' . $element->getName() . '_start')?>).show();
$(<?=json_encode('#_custom_daterange_' . $element->getName() . '_end')?>).show();
} else {
$(<?=json_encode('#_custom_daterange_' . $element->getName() . '_start')?>).hide();
$(<?=json_encode('#_custom_daterange_' . $element->getName() . '_end')?>).hide();
}
});
});
</script>
<?php
$this->layout()->headJavascript .= ob_get_clean();

?>
<table id="_custom_daterange_<?=htmlentities($element->getName())?>">
<tr>
<td><?=$element->getLabel()?></td>
<td><?php
echo $this->{$element->helper}(
$element->getName(),
$element->getValue(),
$element->getAttribs(),
$element->getMultiOptions()
);?>
</td>
</tr>
<tr style="display:none" id="_custom_daterange_<?=htmlentities($element->getName())?>_start">
<td><label for="<?=htmlentities($element->getName())?>_start">Start: </label></td>
<td><input id="<?=htmlentities($element->getName())?>_start" name="<?=htmlentities($element->getName())?>_start" type="text"></td>
</tr>
<tr style="display:none" id="_custom_daterange_<?=htmlentities($element->getName())?>_end">
<td><label for="<?=htmlentities($element->getName())?>_end">End: </label></td>
<td><input id="<?=htmlentities($element->getName())?>_end" name="<?=htmlentities($element->getName())?>_end" type="text"></td>
</tr>
</table>
<div class="error bold"><?=$this->formErrors($element->getMessages())?></div>
<div class="hint"><?=$element->getDescription()?></div>

Unfollow everyone on formspring

I’ve been creating accounts on various social networking sites lately for a project we’re working on, and I somehow managed to bulk-follow over a thousand people on formspring.me with their “find friends” tool. Like seriously, I was following hundreds of Asian teenagers — no idea how that happened.

No worries though, I just fired up jash and jquerify (a no-conflict version, since formspring.me uses prototype, which jquery doesn’t always play nice with) to bulk unfollow all of them.

Once you get jquerify and jash up, just put this bad boy in jash, and you’re good to go:

$jq.each($jq(".unfollow"), function() {
	var str = this.id.split('-');
	fspring.unfollow(str[1],this,'People-View');
});
Unfollow all on Formspring - screenshot

Unfollow all on Formspring

Be prepared to wait!!

Zend_Form_Element_Hidden not really hidden

The point of having a hidden field is that it is truly hidden, and doesn’t require labels / etc. Unfortunately, Zend_Form_Element_Hidden doesn’t really recognise this. Here’s how to subclass it and get rid of that stuff so you can create an input that is hidden for real:

class M_Form_Element_Hidden extends Zend_Form_Element_Hidden {
   public function init() {
      $this->setDisableLoadDefaultDecorators(true);
      $this->addDecorator('ViewHelper');
      $this->removeDecorator('DtDdWrapper');
      $this->removeDecorator('HtmlTag');
      $this->removeDecorator('Label');
      return parent::init();
   }
}

Autoload PhpThumb with Zend Framework

Here’s an easy way to autoload PhpThumb (an excellent & fast image resizing / manipulating PHP library) using Zend Framework without having to modify the PhpThumb source at all. First we need to make our own custom autoloader:

class M_Loader_Autoloader_PhpThumb implements Zend_Loader_Autoloader_Interface {

   static protected $php_thumb_classes = array(
      'PhpThumb'        => 'PhpThumb.inc.php',
      'ThumbBase'       => 'ThumbBase.inc.php',
      'PhpThumbFactory' => 'ThumbLib.inc.php',
      'GdThumb'         => 'GdThumb.inc.php',
      'GdReflectionLib' => 'thumb_plugins/gd_reflection.inc.php',
   );

  /**
   * Autoload a class
   *
   * @param   string $class
   * @return  mixed
   *          False [if unable to load $class]
   *          get_class($class) [if $class is successfully loaded]
   */
   public function autoload($class) {
      $file = APPLICATION_PATH . '/../library/PhpThumb/' . self::$php_thumb_classes[$class];
      if (is_file($file)) {
         require_once($file);
         return $class;
      }
      return false;
   }
}

Then simply put this in your Bootstrap:

Zend_Loader_Autoloader::getInstance()->pushAutoloader(new M_Loader_Autoloader_PhpThumb());

Done. Now you can use PhpThumb in your controllers like this:

class PhotoController extends Zend_Controller_Action {
   public function indexAction() {
      $this->_helper->layout()->disableLayout();
      $this->_helper->viewRenderer->setNoRender(true);
      $thumb = PhpThumbFactory::create("/path/to/image.jpg");
      $thumb->adaptiveResize(250, 250);
      $thumb->show();
   }
}

Script to generate command to push MySQL database changes between enviornments

Got sick of manually doing database dumps between our production, test, and development environments, so I just wrote a very handy script using Zend Framework to generate a command to push changes between environments as you make them.

You will have to tweak ssh_to to suit your needs (our test and production dbs are not separated at the moment, so that removes a layer of complexity for us), but if you have everything setup in application.ini like most people do, this should work almost out of box. You’ll need to setup the autoloader on your own.

usage: php push_db.php --to=dev --from=prod

Enjoy!

#!/usr/bin/env php5
<?php
require_once(getcwd() . '/autoload.php');

$opts = new Zend_Console_Getopt(
   array(
      'from=s'    => 'From environment, with required string parameter',
      'to=s'        => 'To environment, with required string parameter',
   )
);

$from = $opts->getOption('from');
$to = $opts->getOption('to');

foreach (array('from','to') as $env) {
      if (!in_array($$env, array('production','prod','testing','test','development','dev'))) {
         die('Error: invalid parameter ' . $env . " = '{$$env}'" . PHP_EOL);
      }
}

$prod_env = new Zend_Config_Ini(APPLICATION_PATH . '/configs/application.ini', 'production');
$test_env = new Zend_Config_Ini(APPLICATION_PATH . '/configs/application.ini', 'testing');
$dev_env = new Zend_Config_Ini(APPLICATION_PATH . '/configs/application.ini', 'development');

$to_server = array();
$from_server = array();
foreach (array('from','to') as $serv) {
   $server = $serv . '_server';
   switch ($$serv) {
      case 'production':
      case 'prod':
         ${$server}['host'] =                   $prod_env->database->params->host;
         ${$server}['username'] =                   $prod_env->database->params->username;
         ${$server}['password'] =                   $prod_env->database->params->password;
         ${$server}['dbname'] =                   $prod_env->database->params->dbname;
         ${$server}['ssh_to'] = 'me@foobar';
         break;
      case 'testing':
      case 'test':
         ${$server}['host'] = $test_env->database->params->host;
         ${$server}['username'] =                   $test_env->database->params->username;
         ${$server}['password'] =                   $test_env->database->params->password;
         ${$server}['dbname'] =                   $test_env->database->params->dbname;
         ${$server}['ssh_to'] = 'me@foobar';
         break;
      case 'development':
      case 'dev':
         ${$server}['host'] = $dev_env->database->params->host;
         ${$server}['username'] =                   $dev_env->database->params->username;
         ${$server}['password'] =                   $dev_env->database->params->password;
         ${$server}['dbname'] =                   $dev_env->database->params->dbname;
         ${$server}['ssh_to'] = 'me@foobar';
         break;
      }
}

print "Run this command on " . $from . ':' . PHP_EOL;
echo 'mysqldump -u ' . $from_server['username'] . ' -p' . $from_server['password'] . ' ' . $from_server['dbname']
. ' | ssh ' . $from_server['ssh_to'] . ' "mysql -u ' . $to_server['username'] . ' -p' . $to_server['password'] . ' ' . $to_server['dbname'] . '"' . PHP_EOL;


Spotadoink

As small after-work project inspired by FitFinder (which, unfortunately, has since been taken down per the demands of the UCL), several months ago Montmere Limited launched spotadoink, the 21st century catalyst to flirting.

It was hastily thrown together in just a few short hours, but the concept is fun: when you see someone who is attractive, tell the world where!

Unfortunately it has not seen much use since its launch, but as with anything else, who knows what the future holds.