Zend Framework – Internet Strategy Guide https://phpprotip.com Together we can defeat the internet Tue, 07 Mar 2017 02:01:20 +0000 en-US hourly 1 https://wordpress.org/?v=4.7.29 55205001 Copyright © Internet Strategy Guide 2013 chance@chancegarcia.com (Internet Strategy Guide) chance@chancegarcia.com (Internet Strategy Guide) http://phpprotip.com/wp-content/plugins/podpress/images/powered_by_podpress.jpg Internet Strategy Guide https://phpprotip.com 144 144 Together we can defeat the internet Internet Strategy Guide Internet Strategy Guide chance@chancegarcia.com no no Auth/ACL implementation strategies https://phpprotip.com/2010/08/authacl-implementation-strategies/ https://phpprotip.com/2010/08/authacl-implementation-strategies/#comments Mon, 09 Aug 2010 18:52:21 +0000 http://phpprotip.com/?p=384 I’m going to talk more about ACLs than Auth. Auth is simple, it’s the ACL that will trip you up.  Since both concepts are coupled together when you’re making a login system, I feel it’s appropriate to at least touch on Auth. What I want to cover is the ways we can create the ACL object to suit needs based on the scale of the project. I’m going to assume that readers have a passing familiarity with using the Auth and Acl objects and may have even implemented them into projects.

Zend_Auth

The reason I say Auth is simple is because Zend Framework makes it simple with their Zend_Auth class. You can pick an auth style, implement and then go from there. For the purpose of this discussion, I’ll be talking using Database authentication. So after one has set up a login page that uses Zend_Auth (there are already a lot of articles that cover this so i’ll move on), the major bear you have to tackle is using the Zend_Auth_Result to determine proper access. Sounds simple, that’s what Zend_Acl is for.

Zend_Acl

So how do we create our Acl? Again, ZF’s reference guide gives us some handy-dandy examples of using their object but how you utilize the object depends on your scale. Other articles give you a way to bind the two together, usually via a controller plugin of some sort. The thing that can be tricky is how you want the Acl and Auth to interact with each other within that plugin. I utilize a controller plugin that fires off an Auth/Acl check in the dispatchLoopStartup() method. If no Zend_Auth_Result object exists, it assigns a guest role and if one does exist, it searches the Zend_Auth_Storage for a role value (assigning guest if one doesn’t exist somehow) and checks that value against the Acl that was created in my Bootstrap. My biggest conundrum has always been translating Requests into Resources. I’ll talk more on that later viagra from india.

Scaling

I tend to put my scaling into one of the following categories: small,decent or ZOMG. Small is something like a personal site or a proof-of-concept/self-tutorial project where my users will probably be a 1-5 roles and 1-5 resources at best. Decent is most collaborative niche projects with 50-100 resources. ZOMG is where the number of resources I’m dealing with is >100, unknown or potentially large. I define my ACLs in my Bootstrap in one of three ways:

  1. Hardcoded
  2. As part of my Navigation Object properties
  3. Pulled from a database

Hardcoded

This one is easy to implement since if you follow the ZF reference or the numerous guides/posts you find when you google for auth/acl systems, you’ll be able to hardcode your ACL. I find this ideal for small projects where the number of resources is relatively low and the growth of adding additional resources is non-existent. This is the simplest way to do things.

Navigation-based

This method makes use of the Zend_Navigation object. Brandon Savage wrote up a nice guide to integrating ACLs into you r Navigation. I usually instantiate my Navigation objects in the Bootstrap from a XML file. The only tricky thing I found with this is finding the appropriate Navigation_Page (that tells us our resource/permissions) from the Request object. I tend to utilize this method when the growth of resources occurs at a slow pace.

Database-driven

This particular method is what spurred me to write about Auth and Acl. I see this solution as ideal for a high amount of resources or where the growth of resources to have fast spurts.  This solution can allow for ease of maintenance and is scalable. Even though it is a scalable solution, I kind of see it as overkill for smaller, low-growth projects.

Multiple project ACLs

Since I’ve began working with Zend Framework, I have used it to create both internal apps in addition to running my company’s main site. To date, I have a total of eleven internal applications, some of which require Auth/Acl and some of which do not. Those that do not require them will soon be requiring them due to future features we wish to implement for them. At first I was working on a drag and drop solution for setting up an Auth/ACL system for any given project. I was going to work it a stand-alone module where all the developer has to do is call the Module Bootstrap within the Application Bootstrap. The drag and drop solution was going to rely on the project’s Navigation object for determining the ACL of a requested page. Then it occurred to me that even if I could make this ‘simple’ drag and drop solution, we’d be faced with reapplying it to ten more projects and have subsequent setup processes for each additional project. This seemed highly inefficient and a pain in my ass.

Control Panel

My next realization was that there was multiple overlap on the users accessing various internal applications and way too many vhosts to make for each project. It seemed like it would be better to do the ultimate refactor and create a centralized control panel for people to authenticate and access internal applications.

I was still hung up on wanting to reuse my Navigation based code when I figured out that maintaining the navigation XML would be another nightmare. I had attempted a database solution for one project and it became a pain to maintain the ACL when I introduced Routing to the project. It was a bitter and hateful experience to get it working and since both the Auth/ACL and Routing parts of the project were done before I had embraced unit testing, sorting through my crazy monkey patching logic would only intensify my rage. I also recalled that the biggest issue with that proto-solution was translating the Request into a Resource.

In the schema shown on the right, the Resource.Name corresponded to the Request’s Controller and Privilege.Name corresponded to Request’s Action. When the ACL was created in the Bootstrap, it would create Module.Name_Resource.Name as the resource then associate privileges to that resource. Routing and Controller forwarding made this whole thing hard to mentally track. I ended up having a lot of monkey patch entries to make it work in the end.

So here I was, just generally damned when I thought up a way around the issues I had with the previous schema. I would need to have the Resource.Name independent of the Request URI in order to avoid routing issues. By associating the Resource to a URI, I don’t have to account for if Routing exists or not. The URI will always be available and the core ACL system will be independent of any Routes that do/don’t/might exist. Privileges bound to action seemed like a lot of overkill since all privileges come down to CRUD (though I always like the BREAD acronym better). In addition, privileges would be off in their own world and reused when necessary (the last schema had too many redundant privileges associated to different resources).

As I stated earlier, the goal is a unified login for internal apps (there are currently eleven and this number will grow). The user table consists of a username, password and control panel role. This role allows for future interfaces to be built that can manage the control panel such as adding a project or adding users. If you’re wondering why I have the password column as able to be null, it’s to support some legacy items. Next major table is the project table which lets me have a project_user table  that is also has a role associated with it. I made role a separate table since a lot of the projects overlap on roles such as guest and admin. Resources can be specifically named or generalized as necessary. All my links (URIs) can share a resource name if necessary. Finally there is the privilege table along with a resource_privilege table that allows me to maintain those relationships. While I have a separate control_panel_role, I decided that the control panel resource/privilege system doesn’t need to be separate. I only wanted to make sure that the control panel system was accessible even if there was no projects available for selection. I’m planning on making the past projects into modules under this system and all future internal apps accessible/controlled from here. I lack any co-workers that I’m able to debate the merits of this idea with and given that this will be a major refactor of my work thus far, I am asking for feedback on the idea. Am I missing any other viable ways of defining the ACL that would be easier/better? I’m not a DBA so I’m wondering if my tables are actually optimized well enough. Any other issues or thoughts I haven’t considered?

Enhanced by Zemanta
]]>
https://phpprotip.com/2010/08/authacl-implementation-strategies/feed/ 3 384
tekx – zend_form https://phpprotip.com/2010/05/tekx-zend_form/ https://phpprotip.com/2010/05/tekx-zend_form/#comments Wed, 19 May 2010 16:16:35 +0000 http://phpprotip.com/?p=219
Image of Rob Allen from Twitter
Image of Rob Allen

Trying to record @akrabat‘s talk about zend_form but didn’t get good camera placement. Won’t be able to put up the video I do have until after Amsterdam. Will need to get a voice recorder instead.

Filters are destructive. This is important to know that. Validators only reject data. Decorators are used for form rendering. Apparently I’m not the only one confused by it because Rob Allen said we’ll go over that extensively. Zend_Form decorators are a combination of Decorator and Strategy Pattern.

Creating form is as easy as extending the form and sticking things in init(). Form elements implements the fluid interfaces so you can chain methods. When creating an enlement, the name you pass into the constructor will become the name of the element. Validators can be added with the string name or the class itself. After making the element, don’t forget to add it to the form. Caveat on Submit, setLabel() will change the value. Be sure to setIgnore() to true because you won’t care about the value of the button. This is a new hint/trick that I had missed in the past. This is helpful.

Now we’re going over an action code example. Basic stuff you can find from the manual on the Zend Framework site. View examples from the site as well. You can echo out the form only or by element in your view. “Under no circumstances display the email address validator to your customer.” How do you fix it? “Translate” the errors. Create a translate object. Set the translator to the form via the form’s setTranslator() method. If you have a lot of forms, you can use the static setDefaultTranslator() method.

On to the meat of the talk (in my opinion), Decoration. =D

Default element decorators

  1. ViewHelper
  2. Errors
  3. Description
  4. HtmlTag
  5. Label

Order is very important. They render inside out. Even though the label is last, it prepends itself before the element. When things don’t go correctly, it’s ALWAYS because you fucked up the order. Adding a required asterick can be set by retrieving the decorator via getDecorator() and set the option requiredSuffix.

Using LI Instead is clearing the decorators then adding the new ones. You render the  label then the html tag decorators. That’s the difference. is the last 2 in the above list is flipped. (I’ll try to add code examples later or a link to the slides if they’re available.)

On to form decorators.

Default Form Decorators

  1. FormElements
  2. HtmlTags
  3. Form

Once you understand how things work, they’re relatively consistent. Again, for lists, clear the decorators in the init and add them with your tag using ul.

Going over custom elements. Demo is a YesNo element to set radio multiOptions. Setting the separator on this element with a space will get rid of the <br/> tag that is rendered by default. A ThumbsUp decorator is being used as an example to overriding the render. One interesting I just learned is if there are messages present, that is because a validation failed. That makes sense and can be used for finding out if there are errors.

While it seems like it is complex to do via the object when you could do HTML, the validators and filtering are really great for getting good data. This is what makes most of the ‘work’ with Zend_Form worthwhile. Really great talk, being here for this talk justifies my trip out here. I’m hoping all the other sessions level out the conference price tag as well. In 1 hour, I finally understand Zend_Form decorators which I’ve spent countless hours trying to understand. The key is the order of the decorators set and the slide examples on how they render was really helpful and I look forward to if they become available for posting. I’ll have to ask if they’re available later this year.

Part of the questions lead into SubForm which isn’t discussed here. SubForm is useful for multi-page forms. One difference is in the decorators because you only need 1 <form> tag for your form. Also, I think the naming changes if I recall correctly. You can an element named person[name]. I know SubForm is part of the solution to get that naming convention because I’ve used it in a project but would have to look at my source to give a clear example on how to do it.

Reblog this post [with Zemanta]
]]>
https://phpprotip.com/2010/05/tekx-zend_form/feed/ 1 219
tekx – best practices https://phpprotip.com/2010/05/tekx-best-practices/ https://phpprotip.com/2010/05/tekx-best-practices/#comments Tue, 18 May 2010 20:56:11 +0000 http://phpprotip.com/?p=190
Visualization of the "history tree" ...
Image via Wikipedia

Starting off the best practices with source control @lornajane asked who is using source control and how much of that is using distributed source control. I’m 2/2 so far. woot. For those who aren’t familiar with source control, it creates a history and is a great collaboration tool.

Using source control is being discussed. You create a repository, add your project, check out your project, make changes. You can update to get changes from others then you commit it all back to the repository.

We’re looking at an svn log and will be discussing distributed vs non-distributed systems. Demonstrating a sample diff.

Source control Tool

* Subversion (svn)

* Git (git)

* Bazaar (bzr)

* Mecurial (hg)

Difference ways to interact with source control. Lorna gives a shout out for all the command line user people and is now mentioning IDE plugins, Trac, Tortoise[SVN|Git|Bzr|Hg]. I need to see if there’s a tortoiseBzr for OSX. I’m thinking of moving to Git since that gives my team more GUI tools, love Bzr but haven’t found many tools. Done with that sidebar. On to Centralized Source Control.

Centralized is like it sounds, and is derived from a central repository. @weierophinney is talking about repository usage including features being worked on at the same time with different release times. Talking about long-lived branches with staging towards production. I’ve found that I’m using a bit of both but want to move away from that. @weierophinney agrees and is moving away too. We’re tlaking about release branches now that live in their own timeline. Mentions that Distributed version control’s power lies in large groups with lieutenants bringing in changes to the project.

@weierophinney talked about most people moving from a central to distributed. I personally just used distributed and didn’t find it tough to pick up but do agree that if you started on central, you have a finer appreciate for the power distributed has.

Reviewing bridges such as git-svn and bzr-svn. Zend Framework 2.0 is on git and 1.x is on svn and they’ve been using the bridges to transition. Now @lornajane is plugging her use of bzr-svn. Just heard the term “continuous integration” used. Is it me or does anyone else consider this a buzzword now? We should make a buzzword bingo game for these talks…just saying.

Going over Hosted Solutions for authoritative sources such as github, bitbucket, googlecode, launchpad, sourceforge. Maybe I should plug @haralovich‘s bzrhive, maybe that will move his ass towards finishing so i don’t have to move from bzr to git. what is bzrhive? think what github is to git, bzrhive will be for bzr. people should harrass/help @haralovich make it happen.

Bazaar
Image via Wikipedia

Heard: If you’re not using source control, you’re doing it wrong nub. (not an exact quote)

goinv over resources including tek talks, subversion books, comparison of tools can be found on wikipedia.

On to discussing coding standards.

You don’t have a standard when…

* you always reformat code you get from others

* code you wrote 6 months ago looks different from what you write today

* it introduces a syntax error

I can see that list becoming a meme.

Coding standards assist in maintainability and collaboration. Maintainability provides sttructured predictability. Collaboration is aided by letting any developer can pick up and read it which means

* anyone can maintain it

* decentralizes responsibility

* issues and features are quicker to implement

There are 2 pillars of coding standards but i missed the bullet points on that. =(

ack, messed up my text and missed more thing. lesson learned, save often and wish that this post was version controlled so I could roll back.

Design Patterns isn’t rocket surgery. They’re a common way to describe a common problem which gives us a shared language. Allows you to be put in a position to be able to research best solutions. It’s not just only found in PHP but shared across languages. It is heavily OOP.

common patterns

  • factory
  • registry
  • adapter
  • decorator (can be visually decorative but not always)
  • observer

factory has methods to creat and return objects. It can return different objects, may use complex logic to work out what to do thus eliminating using a switch to do this. Example is a hat factory. I’ll let people look up patterns because they should and the slides are going pretty fast to parrot back on this post. @lornajane is using SOAP to REST as an example to adapter pattern. This is real life example. If i’m remembering correctly, she wrote a series on her blog on this. I’ll have to see if i can dig that up and link if relevant.

“The root problem is the client came across a little bit of knowledge” – @lornajane

Going over decorators which is making me want to attend the zend_form session by @akrabat so that I can maybe get some insight into the form decorators. Need to see who’s going to the other sessions and get recordings if possible. Should also check with @akrabat if I can record so that I have a bartering chip for some recordings.

Observer pattern watches for changes in another object and responds to those changes. Target class is aware and notifies the observing classes. Example is a map whowing where event attendees are located. If they’re wanting to track traffic, they could ask @dragonbe about that. word on the street is he might know something about that. 😉

Back on topic, I’m thinking I need to look over some of my classes and implement observer strategy. Mention of resources such as the Gang of Four, martin fowler and @sweatje’s own book.

http://www.fluffycat.com/PHP-Design-Patterns/ is a ridiculously silly domain name but also is apparently a good resource.

Documentation via API Docs. Specifically talking about PHPDocumentator found at phpdoc.org. If there’s no code comments, then it uses reflection. PHPDoc output can be generated via command line, web interface and there’s some IDE plugins for it too. One thing to note is that PHPDocumentator isn’t upgraded to php 5.3.

End user documentation. bwah? Oh, narrative documentation for developers such as a wiki. Issues with using a wiki is that it’s un-distributable and un-versioned. HTML is another option but hard to offer in alternate formats (e-reader, windows help system, etc). Docbook XML is yet another option, nice thing is you can use XSLT on it for alternate formats. Looking at an example of Docbook. I’m sold, going to start using that for my projects. Remember to do programming examples as cdata.

tools you’ll need:

  • xsltproc
    • http://xmlsoft.org/XSLT/xsltproc2.html
  • phd (PHP Documentor)
    • http://doc.php.net/phd/docs/

Going beyond API Docs include doing tutorials, installation instructions, examples, FAQs, forums and user-contribution.

This segues into you (and me) becoming a user-contributor. How? Answer forum questions, hang out on the IRC channel. Help with official project documentation. blogging. @lornajane uses her blog like I do/mean to…as a substitute for a brain. Write for your own use and it hope it’s useful to other people.

Looks like they may be saving the best for last, Testing. Disappointingly, there wasn’t many hands raised when asked who’s doing unit testing. I’m proud to say that I was one of thoe hands raised. So, let’s go on to why you should start. First reason is maintainability (see the slide b/c I was too busy patting myself on the back to catch reasons listed on the slide). Testing quantifies the quality of your code. Kitty photo I want permission to insert here that illustrates the fuzzy feeling you get when your tests go green.

what is not testing

  • reloading your browser
  • var_dump

Testing is

  • reproducable
  • automatible

Good testing has defined behaviors, code examples of use cases and expectations.

Testing frameworks available

  • PHPT – used by PHP project, some PEAR libraries. neat b/c it’s php using itself
  • SimpleTest – JUnit style testing framework
  • PHPUnit – JUnit style testing framework; de facto standard

How to test? Create a test case class (usually named after unit or class you’re testing). Think about the behavior you’re testing and state it in your native language. Create a method named after the behavior. capture the code that should create the behavior. Create assertions indicating the expected results. When the slides come up, you’ll have a visual on this with an example that was given in the talk.

Once you’ve built the test case, you run the test. If it fails, then you get to check the test assumptions and assertions then you check your code. Rinse. Repeat. Beer. WIN.

Other Testing Topics includes test doubles (stubs and mock objects). Doubles are amazing but I found the learning curve for me was steep but once I got it, it was the greatest feeling in the world and has made the speed of my testing incredibly quick. If you’re getting into testing, there is a curve and it is time intensive. Stick with it, it is worth every second you spend. It may seem like it takes more time to be worthwhile but as you get more practice, you get a return on that time.

Moving on to Test coverage, conditional tests (useful for environmental conditions). Functional and Integration tests allows you to test systems a unit interacts with all respond expected. This is a scary step. I’m just now trying to get these written for my own systems. Time and budget to do it are hard to find but I have a feeling it’ll be worth it in the end. @weierophinney mentioned Selenium and some other tools that can help with this. Learned about Selenium last year but haven’t looked into it since then.

Adding tests to existing, untested projects is a huge barrier of entry. Best way to handle this is to create tests as you add new features. When you fix a bug, make a test.

Talking about TDD. I agree that once you start using it, you can’t go back. You capture behaviors and individually and iteratively in unit tests. You define your API before to committing to coding them. The biggest help is that you can refine some business logic or how class interaction works. Talking about breaking down tests, we touched upon striving for “one assertion per test” that’s been discussed before.

Bottom line on testing: test early and often.

Looks like I was wrong on testing being last. Continuous Integration and Quality Assurance(?) are last. Staring out with static analysis. lines of code was one tool mentioned but I didn’t get the rest (which is fine since they’ll go through them and I’ll write about them below). Lines of Code utilizes cyclomatic complexity which helps in auditing your code. I’m kinda scared of running this on some of my code. I think it will trigger some kind of “you’re a nub” message.

Code sniffer is associated with coding standards. it’s configurable to look for different properties. There are some pre-defined standards.

Continuous Integration? bwah?? Originally, automated build systems for compiled languages. Used in PHP to run unit tests, build documentation, etc. Any QA tool you have should hook into your Continuous Integration. System typically monitors commits (remember version control from earlier?). Poor man’s CI system can be done with cron if you don’t have time/inclination to create post-commit hooks. Build will run tests, run QA tools (sniffer,etc), build documentation…

Ant (http://ant.apache.org) is one solution. Ant isn’t CI  by itself but a build system. Phing (http://phing.info/trac) is a PHP Ant clone.

CruiseControl (http://cruisecontro.sourceforge.net) uses Ant under the hood but is the first CI solution presented. Has a browser based interface which looks sexy. Next option up is phpUnderControl (http://www.phpundercontrol.org) which is a superset of CruiseControl with built-in support for PHPUnit, CodeSniffer, and more.

Hudson (http://hudson-ci.org) which is an oracle OSS project, written in Java. Uses Ant for build configuration. PHPUnit support via a generic xUnit plugin and supports other PHP tasks via Phing.

Bamboo (http://www.atlassian.com/software/bamboo/) is a commercia Java solution. Uses Ant or Maven. Most PHP QA tools export logs to formats compatible with equivalent Java tools; Bamboo simply uses these logs.

Continuous Integration is about automation to help you find issues early and fix them before deployment. Use CI solutions to perform the automation.

Check out http://phpqatools.org and http://phpqabook.com as well as Sebastian Bergmann’s talk “The State of QA tools…”

Oh, last topic is Deployment. That makes sense. Tools include hand-spun scripts (done this when I was at Resite), Phing, Capistrano (which is Ruby…wonder what @tychay has to say about this. bet he already has said something. ^^)

They may have skimmed a lot of the topics discussed but damn, did they skim them well. For a lot of stuff I already knew or read about, they managed to hold my interest and keep me awake. As @kevinbruce tweeted, it was very intensive and awesome.

Reblog this post [with Zemanta]
]]>
https://phpprotip.com/2010/05/tekx-best-practices/feed/ 1 190