archive-com.com » COM » B » BENRAMSEY.COM

Total: 425

Choose link from "Titles, links and description words view":

Or switch to "Titles and links view".
  • PHP’s Not Just a Language, by Ben Ramsey
    a community PHP is a lot like the English language It began its life as a utilitarian language serving a simple purpose processing forms on a web page A diverse community grew up around this language further evolving it and changing it to suit their needs to aid in communication After all a programming language is just another means of communication The audience may be different in this case the language is for communicating with a server database and more but the end goal is the same In fact taking this analogy a bit further PHP FI created by Rasmus Lerdorf is like Old English while Andi Gutmans and Zeev Suraski brought about their own Norman conquest of PHP creating Middle PHP PHP 3 0 What we have now with PHP 4 and PHP 5 are the natural progressions of PHP into its modern form PHP has also borrowed from other languages C Java and Perl among others have all influenced PHP The PHP extension API makes it easy to make any C C library available directly from within the PHP language Moreover PHP acts as a bridge to many different protocols facilitating communication between disparate platforms This evolution is possible because of two main traits PHP was designed to evolve The community not a singular language designer determines the direction and future of the language These are not mutually exclusive The language was designed this way on purpose by the community Although the PHP community would not exist without the PHP language the PHP language as we now know it would not exist without the PHP community PHP the language needs the community and PHP the community needs the language A community of diverse backgrounds Once upon a time I wrote a post with the same title as this section heading The premise was that many PHP programmers I know did not start out with the intention of becoming a programmer They had an itch a need to solve a problem and when they scratched it they used PHP PHP has a low barrier to entry It s easy to write apps in PHP It s easy to solve problems with PHP Often this results in some horrid code being released to the public that gets used and reused and becomes wildly popular to the dismay and horror of some Still as I ve heard someone credit Rasmus as saying Who better to write a data filing program than a file clerk PHP allows them to do that This is the spirit of PHP It is a community rich with pragmatism and developers from all sorts of backgrounds with matter of fact attitudes They ll tell you like it is no holds barred But they re also open and welcoming eager to help and instruct in the ways of standards and best practices because at the end of the day we just want you to be the best you can be at your craft Like many communities the PHP

    Original URL path: https://benramsey.com/articles/php-is-not-just-a-language/ (2016-04-26)
    Open archived version from archive


  • Services in the Cloud, by Ben Ramsey
    If porting applications already running across multiple servers then EC2 is a good fit because for the most part you can image those machines and move them directly into EC2 with minimal changes Google App Engine Google App Engine differs from EC2 in that the Google cloud is a full development platform in which you run applications rather than deploy virtual machines App Engine abstracts away the low level details of the operating system removing the need for administration of a virtual machine and allowing you to focus on building applications at a higher level Think of it as a massive operating system that is fully managed by Google Scaling in App Engine happens naturally As your applications need more resources App Engine allocates more Under a certain threshold there is no cost to use the service but as demand on your applications requires resources above that threshold then Google will start charging for resource usage Some of the quotas imposed on the free service include limits on e mails that can be sent per day bandwidth in and out quotas per day CPU megacycles per day HTTP requests per day and data store API calls per day In addition App Engine imposes some hard limits for the service including a maximum of thirty seconds per request 1 000 files per application a maximum of 10 MB allowed in an HTTP response and no more than 1 MB per item stored in the data store Other restrictions include read only access to the file system execution of code only through an HTTP request and data store queries are limited to only 1 000 rows returned per call While there certainly appear to be a lot of limitations and restrictions involved in using App Engine it can save you the hassle of managing a server farm Use App Engine when you don t want to worry with server set up and maintenance you want an environment that already comes complete with helpful APIs and even a built in web application framework and you don t mind programming in Python or Java Other languages will be added in the future perhaps including PHP As a side note it is possible to run PHP on App Engine with Quercus a Java implementation of the PHP language Follow the PHP on App Engine link in the Related Links section for more information Windows Azure A relative newcomer to the cloud game the Azure Services Platform from Microsoft is a collection of various services and APIs that exist in the Microsoft cloud These services include Live Services SQL Services NET Services SharePoint Services and Dynamics CRM Services The hosting and management environment in which these services live is called Windows Azure which is described by Microsoft as a cloud services operating system On top of this plat form and on this operating system Microsoft runs such services as Windows Live Office Live Exchange Online and others and they have opened up the platform allowing developers

    Original URL path: https://benramsey.com/articles/services-in-the-cloud/ (2016-04-26)
    Open archived version from archive

  • OAuth: Under the Hood, by Ben Ramsey
    we ll make as the Consumer to the Provider to obtain the Request Token see Step 2 in Figure 1 Listing 1 POST oauth getRequestToken HTTP 1 1 Host foophoto example com Authorization OAuth realm http foophoto example com oauth consumer key myfoolife example com oauth nonce 37c0712e605ff858f26211323adddcb3 oauth signature method RSA SHA1 oauth timestamp 1234822009 oauth version 1 0 oauth signature IgJbu19VwYBXyRAautunRRKfCfc2pD 2B3 Content Length 0 If all goes well and our OAuth parameters and sig nature check out FooPhoto will return a response including the oauth token and oauth token secret parameters This response is Step 3 of Figure 1 HTTP 1 1 200 OK Server FooPhoto Content Type text plain charset UTF 8 oauth token 4 2FPybRyrmTUbAqwU5A eSrUQvwqJu5 oauth token secret fs5sWCIWPmJKmhgNBpguFJ8C User Authentication Now that FooPhoto has given us a Request Token the oauth token returned in the previous response we may now redirect the user to FooPhoto so that they can authenticate with the service and grant MyFooLife access to their protected photos We do this by send ing a redirect response to the user redirecting them to foophoto example org and including the oauth token in the request This response is represented by Step 4 in Figure 1 HTTP 1 x 302 Moved Temporarily Server MyFooLife Location https foophoto example org oauth authorizeToken oauth token 4 2FPybRyrmTUbAqwU5A eSrUQvwqJu5 oauth callback http 3A 2F 2Fmyfoolife example com 2Fmypictures Now the user is no longer on our application They are viewing a page on the FooPhoto website asking them to either log in or if they already have an active session grant MyFooLife access to their protected data Once this process is complete and the user has either granted or denied access FooPhoto redirects the user back to MyFooLife using the oauth callback parameter presented in the previous request The Location contains the Request Token authorized or denied by the user Step 5 in Figure 1 shows when this response occurs HTTP 1 x 302 Moved Temporarily Server FooPhoto Location http myfoolife example org mypictures oauth token 4 2FPybRyrmTUbAqwU5A eSrUQvwqJu5 Requesting the Access Token By now the user has granted permission to MyFooLife to access their photos on FooPhoto Using the Location header given in the previous response the user s browser now sends a request to MyFooLife including the authorized Request Token MyFooLife may now begin the process of obtaining the Access Token which is what we will need to get the user s protected data from FooPhoto Step 6 represents this request GET mypictures oauth token 4 2FPybRyrmTUbAqwU5A eSrUQvwqJu5 HTTP 1 1 Host myfoolife example com Now the magic occurs This is the moment we ve been waiting for The next few series of requests and responses will provide our service with access to the user s photos Listing 2 POST oauth getAccessToken HTTP 1 1 Host foophoto example com Authorization OAuth realm http foophoto example com oauth consumer key myfoolife example com oauth nonce 91a851a9b2710d8a79d2a713a74c25a2 oauth signature method RSA SHA1 oauth timestamp 1234822105

    Original URL path: https://benramsey.com/articles/oauth-under-the-hood/ (2016-04-26)
    Open archived version from archive

  • Amazon CloudFront, by Ben Ramsey
    have not yet created any distributions then there will be no DistributionSummary elements To send this request using the Amazon CloudFront library simply call the getDistributionList method on the Amazon CloudFront object This will return an Amazon Distribution List object which extends PHP s ArrayObject so it may be iterated over as seen in this example list cloudfront getDistributionList foreach list as distribution echo distribution getId n echo distribution getConfig getOrigin n echo distribution getDomainName n n You ll also notice several other elements in the response Marker MaxItems and IsTruncated CloudFront uses these for pagination of the distribution list For example you may pass Marker and MaxItems as query string parameters in the request Their respective XML elements will be populated with the values passed If there are multiple pages of results then IsTruncated will contain the value true and a NextMarker element will be set allowing you to pass its value as the Marker parameter of the query string when retrieving the next page of results Creating a New Distribution When you first set up your Amazon CloudFront account you won t have any distributions To create a distribution make a POST request to the 2008 06 30 distribution URI and include an XML document with a root DistributionConfig element Listing 2 POST 2008 06 30 distribution HTTP 1 1 Host cloudfront amazonaws com Date Sun 28 Dec 2008 22 54 11 GMT x amz date Sun 28 Dec 2008 22 54 11 GMT Authorization authentication string Content Length 326 Content Type application xml Connection close xml version 1 0 DistributionConfig xmlns http cloudfront amazonaws com doc 2008 06 30 Origin benramsey s3 amazonaws com Origin CallerReference 20081228175411 CallerReference CNAME cdn benramsey com CNAME Comment benramsey com static elements Comment Enabled false Enabled DistributionConfig HTTP 1 1 201 Created ETag EZWBJQXKK6SDH Location URI of new Distribution Content Type text xml Transfer Encoding chunked Date Sun 28 Dec 2008 22 54 11 GMT Server CloudFront XML document with Distribution root element Listing 2 shows the raw HTTP request for creating distributions The following code shows how to create this request using the Amazon CloudFront library require once Amazon CloudFront Distribution Config php config new Amazon CloudFront Distribution Config config setOrigin benramsey s3 amazonaws com config setComment benramsey com static elements config addCname cdn benramsey com distribution cloudfront createDistribution config Each CloudFront distribution must be associated with exactly one Amazon S3 bucket Notice that the S3 bucket associated with this distribution is benramsey s3 amazonaws com You may optionally set a comment enable the distribution to accept requests or add up to ten CNAME records to associate with the distribution Using a Distribution When the response comes back from the server it s in the form of a Distribution element Two important child elements to note are Id and DomainName Id is the identifier of the distribution and you ll use DomainName in your applications to reference objects in the distribution or more specifically the objects stored in the origin

    Original URL path: https://benramsey.com/articles/amazon-cloudfront/ (2016-04-26)
    Open archived version from archive

  • Grokking the REST Architectural Style, by Ben Ramsey
    RPC focus on the diversity of actions that the application can perform giving rise to disparate systems across the network that all require different interfaces to communicate with each other the REST style simplifies interactions by defining a uniform interface between components This allows independent components such as the client or server to change while maintaining the same interface Also the same request may be made to other servers in the network and each receiving server can understand the request They may not be able to fulfill the request but they all can understand it Fielding describes the uniform interface of REST as being composed of four constraints identification of resources manipulation of resources through representations self descriptive messages and hypermedia as the engine of application state Identity Matters The first interface constraint identification of resources is often described as two separate topics when discussing REST resources and addresses Yet these are one and the same in the context of the REST style since a resource must have an address Another word often used in the place of resource is noun Resources are all around Take a look I dare you Every object you see is bound to be a resource The monitor in front you The pen lying on top of the notepad that is sitting in your letter tray on your desk These are all resources and you ll be hard pressed to find something that isn t a resource but what makes a resource a resource Wiktionary defines a resource as something that one uses to achieve an objective With this broad of a definition practically everything can be considered a resource because everything can be used to achieve some objective or another My monitor conveys information from the computer in a way that I can understand I use the pen to write in the notepad which I use to store my notes The letter tray holds papers and in my case mostly junk and I use the desk as a workspace that supports my computer and all the resources I need to do my work In our case though we re not talking about tangible resources physical objects one can touch and interact with in the physical world Rather we re interested in virtual resources on a network like a document image or service If you can request it over the network it s a resource but a better way to define these types of resources is if it has identity it s a resource Identity matters When thinking about physical resources a particular resource may or may not have an identity that specifies its location in space Certainly our brains give objects a kind of identity Please pick up the pen that is on top of my desk Which pen The one lying next to the beer glass Oh That pen Objects in the real world have spatial identity This is the same for resources in a network but the space is virtual and the address identifying a resource s location is more exact On the Web we re familiar with a Uniform Resource Locator URL as an address for a resource In the REST style the focus is on resources and their identifiers rather than on methods and actions The diversity of resources is an important concept since the network is capable of expanding to an infinite number of resources A RESTful system should expose these resources through hypermedia which will be discussed later under Resources Are Related and all resources should share the same interface for access and transfer of state Clients may get resources update them and delete them In addition clients may create resources These are analogous to the HTTP methods GET PUT DELETE and POST Without addressable resources with a uniform interface there is no way for clients to make requests of servers so the client server relationship again is crucial to this constraint of the REST style One Identity Many Representations The second interface constraint is that of representations Each resource has a representation such that the client never requests the resource itself but a representation or a concept of that resource This allows the server to respond dynamically through content negotiation with a representation that satisfies the requesting client There is never a need to change the links to the resource when the representation changes The identity remains the same though the representation changes In the REST style whenever actions are performed on a resource the client uses a representation of the current state of that resource and transfers that representation to the server to communicate a change in state This is where the REST style gets its name This is representational state transfer the act of manipulating resources over a network by transferring representations between components to communicate changes in state Representations of resources are made up of media types on the Web the most common of which is text html but others specifically those common in web services might include application xml application xhtml xml application atom xml application soap xml application json and others including binary media types such as images These media types all compose hypermedia elements of a greater hypertext system Resources Are Related Hypermedia the third interface constraint is important in RESTful systems because the REST style places emphasis on the links between resources In HTML the most familiar links between hypermedia resources are found in the href attribute of the a element These links allow users to move between resources as they wish In a RESTful service resources should be linked together Besides HTML an excellent example of a format that makes use of links is the Atom Syndication Format RFC 4287 Atom provides link elements that use rel attributes to specify relationships to the current resource Listing 1 provides an example Atom Entry document with link elements for various types of related resources An Atom client uses this information to expose these links to users Listing 1 xml version 1

    Original URL path: https://benramsey.com/articles/grokking-rest/ (2016-04-26)
    Open archived version from archive

  • Practice Safe Idempotent Methods, by Ben Ramsey
    example it s exists temporarily at another location specified by the Location header The browser knows what to do with this so it makes a second request for http phpadvent org 2008 Through telnet we can make the raw request like this GET 2008 HTTP 1 1 Host phpadvent org What we get back is a 200 OK response with a full HTML body This is standard redirection I make a GET request and the server tells me to request from a different location The server itself does not perform the redirection That is up to the client browser Safety First I won t spend too much time talking about what GET and POST mean You already know these methods The GET method is used for retrieval while the POST method is used to indicate a resource on the server that should take care of processing some data that we re sending to it What s important to note here is that the HTTP specification clearly states that GET SHOULD NOT have the significance of taking an action other than retrieval Steps up on the soap box Web developers violate this every time we create a link on a page that a user clicks on to rate something increase a counter purchase a book etc The fact of the matter is this if it uses a GET request to take any action other than retrieval then it s wrong But why is it wrong you ask It s not wrong because someone sat in their ivory tower and mandated that it is so The HTTP designers designed GET as a safe method allowing browsers to represent POST in a special way to make the user aware that they are requesting a potentially unsafe action This does not mean that GET cannot have side effects on the server but it does mean that the user may not be aware that the request for those side effects was made and cannot be held responsible for it If web developers forced the use of POST for these kinds of actions rather than using GET requests then the browser could at least notify the user that some action is about to be made and they could confirm or cancel the request Idempotence Not a Sexual Dysfunction This leads to the concept of idempotence Pronounce it at your own risk HTTP methods that are said to be idempotent are so termed because aside from error or expiration issues the side effects of N 0 identical requests is the same as for a single request In layman s terms what this means is when I make a request ten times the side effects of that request are exactly the same on the tenth time as they are on the first time GET is considered idempotent as are HEAD PUT and DELETE which I won t be discussing in this post POST is not idempotent Since GET is considered safe and for retrieval only then it is

    Original URL path: https://benramsey.com/articles/practice-safe-idempotent-methods/ (2016-04-26)
    Open archived version from archive

  • Getting Involved in the PHP Community, by Ben Ramsey
    present at any time this channel has become the primary yet unofficial PHP help channel Training I am often asked about PHP training courses While I do know that some local colleges and universities might provide PHP training courses check with your community college I know mine has PHP and MySQL courses as part of their continuing education program the two most prominent places to get PHP training online are through php architect and Zend Connecting with the Community There are numerous ways to connect with the PHP community The places I list here are merely from my own experience Planet PHP Perhaps one of the best ways to connect with the community is to read what the community has to say Planet PHP is an aggregation of many of the prominent blogs from around the PHP community You ll read PHP tutorials and HOWTOs thoughts about technology plans for the future of PHP and even plans for the weekend PHPDeveloper org PHPDeveloper org is the PHP community s premier news site Collecting the top news stories from around the PHP community on a daily basis PHPDeveloper org keeps the PHP community informed and up to date on the progress of various community projects and events php architect Although reading php architect can be considered a way to get help I consider it an interface to the community which is why I list it here It offers high quality articles and commentary from the PHP industry s top professionals and core language contributors For unique insights into the PHP community be sure to check it out PHPCommunity org For last I save the PHP Community project This project began in December 2003 In my opinion this was the most promising community project that never quite took shape and it has a legacy that no other community site can rival It lives on as the phpc channel on Freenode On this channel you will find many of the movers and shakers of the PHP community hanging out and chatting about everything from database abstraction layers to beer Keep in mind that this is not a help channel it is a community channel And keep this project s web site on your radar as well I hope to see new and exciting things come of it in the coming year Contributing Back to the Community Finally if you fall into the group of those wishing to give back to the community there are a few important places you ll want to visit and some steps you might want to take Start a Blog This is not necessarily the first step to take but it s usually the first thing I tell people who want to get involved in the PHP community in a big way Start a blog make a few friends see the phpc channel above get on their blog rolls help others by writing about your experiences and how you solved particular problems and share informed opinions on topics that

    Original URL path: https://benramsey.com/articles/getting-involved-in-the-php-community/ (2016-04-26)
    Open archived version from archive

  • The Standard PHP Library (SPL), by Ben Ramsey
    those created by using the getIterator method of any class that implements the IteratorAggregate interface Iterator defines methods for traversing an object I ve already mentioned them in passing but for the sake of thoroughness they are current key next rewind and valid Implementing this interface and defining the behavior of each of these methods is enough to get an iterator working but for the most part typical objects will not contain both data and the iteration behavior Thus it may be necessary to abstract out the iteration methods and instead have your data class implement IteratorAggregate IteratorAggregate As mentioned in the previous section it is not always practical or advisable to define the behavior for your iterator inside a data class that represents a model of a type of data For one models in the real world don t necessarily exhibit traversable behavior on their own Instead something else performs the iteration for them The SPL provides such a means for this type of abstraction through the use of the IteratorAggregate interface Example 3 shows how to use this interface by taking the PartyMember class from Example 2 and abstracting out the iteration behavior to a separate PartyMemberIterator class Now the PartyMember class worries only about the data while the PartyMemberIterator handles the traversal of PartyMember data To do this simply define a getIterator method that returns an iterator Example 3 Using an IteratorAggregate php class PartyMember implements IteratorAggregate define the class as usual with properties a constructor getter setter methods etc public function getIterator return new PartyMemberIterator this class PartyMemberIterator implements Iterator public function construct PartyMember member Store member locally for iteration Implement current key next rewind and valid to iterate over data in member member new PartyMember 1 foreach member getIterator as key value echo key value n RecursiveIterator RecursiveIterator defines the interface for recursion through an object with multiple levels of data Think about multidimensional arrays and how foreach handles them Rather than traverse each dimension of the array it stays only at the top level The same can be said of the standard iterator Implementing RecursiveIterator however allows the iteration to dig deep into the tree and iterate through it all This interface itself extends Iterator so it inherits the standard current key next rewind and valid methods but it also defines the getChildren and hasChildren methods which an iterator must implement in order for recursion to take place The getChildren method must return an object that implements RecursiveIterator SeekableIterator Normal iterators must start at the beginning of the sequence of data and progress to the end There is no way for them to begin at a specified place in the data Enter the SeekableIterator The SeekableIterator interface like the RecursiveIterator simply extends Iterator to provide more functionality So while a SeekableIterator has the same methods as an Iterator it also has the seek method which accepts the index of the position to seek If the position does not exist it should throw an OutOfBoundsException Example 4 illustrates how the PartyMemberIterator could be modified as a seekable iterator Example 4 Using the SeekableIterator interface php class PartyMemberIterator implements SeekableIterator public function construct PartyMember member Store member locally for iteration public function seek index this rewind position 0 while position index this valid this next position if this valid throw new OutOfBoundsException Invalid position Implement current key next rewind and valid to iterate over data in member Iterators for All Occassions While the SPL defines interfaces for creating your own iterators it also provides some handy built in classes that can be used to solve standard programming problems There are many of these built in to SPL and I won t take the time to go over them all though I will mention a few that are especially useful ArrayIterator As an internal class ArrayIterator implements SeekableIterator ArrayAccess and Countable This in itself gives this class a lot of power but it goes a little further to implement several of its own methods including append various sorting methods i e asort ksort etc and getArrayCopy Finally the functionality defined by this class allows you unset and modify values while iterating through arrays and objects We can use the party array mentioned earlier to create an ArrayIterator object and manage the array data through the object partyIterator new ArrayIterator party partyIterator asort echo count partyIterator n partyIterator seek 4 echo partyIterator current DirectoryIterator The built in DirectoryIterator class provides an easy way to create a directory iterator and traverse a directory tree complete with the ability to get information about each file or directory in the tree through the use of the SplFileInfo class of which the DirectoryIterator returns objects for each file in the directory All of this is handled in a purely object oriented manner with no need to call PHP functions to get information about the files or to dig deep into the directory Previously such a task required a fair amount of procedural code that we the programmers usually put into custom userland functions for reuse throughout our applications Now all such operations are built into the SPL as Example 5 demonstrates As mentioned earlier the SPL also includes recursive iterators and in this case the built in RecursiveDirectoryIterator can be utilized to traverse an entire directory tree by getting the children of each directory and iterating through them as well Example 5 Iterating through a directory php path new DirectoryIterator path to dir foreach path as file echo file getFilename t echo file getSize t echo file getOwner t echo file getMTime n FilterIterator If you ll notice the output when you run Example 5 you ll see that DirectoryIterator loops through all items in the path including the dot paths for the current and parent directories We could use an if statement within the foreach loop that checks file isDot but ultimately the object still contains these items and that may not be the desired result Thus the SPL introduces the

    Original URL path: https://benramsey.com/articles/standard-php-library/ (2016-04-26)
    Open archived version from archive



  •