Object-Oriented Programming in ColdFusion - Matt Gifford - E-Book

Object-Oriented Programming in ColdFusion E-Book

Matt Gifford

0,0
31,19 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Are you tired of procedural programming or is your extensive code base starting to become un-manageable? Breathe some new life into your code and improve your development skills with the basic concepts of object-oriented programming. Utilize objects, modular components, and design patterns to expand your skills and improve your ColdFusion applications. Packed with example code, and written in a friendly, easy-to-read style, this book is just what you need if you are serious about ColdFusion.This book is a fast-paced tutorial to important ColdFusion object-oriented programming topics. It will give you clear, concise, and practical guidance to take you from the basics of ColdFusion to the skills that will make you a ColdFusion developer to be reckoned with. Don't be put off by jargon or complex diagrams; read and see how you can benefit from this book and extend your development skills in the process.Using the practical examples within this guide, you will learn how to structure your applications and code, applying the fundamental basics of object-oriented programming to develop modular, reusable components that will scale easily with your application. You will learn the basic fundamental practices of object-oriented programming, from object creation and re-use, to Bean objects, service layers, Data Access objects, and sample design patterns to gain a better understanding of OOP using examples that can be altered and applied in your application. Complete with detailed code samples and snippets, and written in a friendly easy-to-follow style, you will be able to break free from writing purely procedural code and enhance your applications by building structured applications utilizing basic design patterns and object-oriented principles.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Seitenzahl: 190

Veröffentlichungsjahr: 2010

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Object-Oriented Programming in ColdFusion
Credits
Foreword
About the Author
Acknowledgement
About the Reviewer
Preface
Who this book is for
What this book covers
What you need for this book
Conventions
Reader feedback
Customer support
Errata
Piracy
Questions
1. Introducing ColdFusion Components
Why use CFCs?
Grouping your functions
Organizing your components
The ColdFusion component tags
Our first component
Defining a method
Returning the data
ColdFusion 9 scripted components
Creating your object
Restricting your functions to scopes
Using arguments within your methods
The Arguments scope
Redefine the function parameters
Combining your methods
Protecting your local variables
Using the Var scope
Placing your Var scoped variables
Naming your Var scoped variables
Accessing your CFC
Instantiating the object
Using the createObject function
Using the cfobject tag
Using the NEW operator
Using cfinvoke
The cfinvoke tag
Using cfinvokeargument
Using attributes as arguments
Using an argument collection
Passing arguments into an instance method call
As a list
As named values
As an argumentCollection
Arguments in action
Merging your functions into one
Using cfargument to combine your methods
Creating an object constructor
Creating an init() function
The Variables scope
Calling your init() function
The This scope
Summary
2. Effective Component Development
Pseudo-constructors
Using the pseudo method
Suppressing whitespace
Output attribute
Pseudo-constructor or init() method
Returning values and variables
returnType
Access properties
Private
Package
Public
Remote
Getting information about your CFC
Introspection
CFC Explorer
Component Doc
Document your code
Benefits of documentation
Displayname attribute
Hint attribute
Description attribute
User-defined metadata
Obtaining CFC metadata
getMetaData
getComponentMetaData
Returning metadata
Detailed introspection
Summary
3. Building Your First Bean
What is a Bean?
But what is it really?
The benefit of using beans
Creating our first Bean
An introduction to UML
Person object in UML
What makes a Bean a Bean
A default/no-argument constructor
Easily accessible for introspection
Setters/Mutators
Getters/Accessors
Completing our Projects Bean
Calling our project Bean
Populating the Bean
Read/Write Bean
Read-only Bean
Helpful objects
Implicit accessors
Summary
4. Inheritance and Object-Oriented Concepts
What is Inheritance?
Avoiding code duplication
Inheriting our products
The Super keyword
Overriding methods
Instantiating our products
The inheritance hierarchy
Specialization
The "IS A" relationship
Polymorphism
Composition
The "HAS A" Relationship
Implied ownership
Aggregation
Summary
5. Data Access Objects
What is a Data Access Object?
Creating a Data Access Object
The create method
Storing a new user
The read method
Handling select results
The update method
The delete method
An alternative save method
The save method
The exists method
Caching the Data Access Objects
Dependency Injection
Summary
6. Gateways
What is a Gateway?
A typical ColdFusion Gateway
Creating a Gateway object
Naming conventions
Adding gateway methods
Minimising code duplication
Revising the gateway object
Caching the Gateway object
The Gateway discussion
No hard and fast rules
Table Data Gateway
Similarities to Data Access Objects
Combining the two patterns
Which option is best?
Summary
7. Creating a Service Layer
What is a Service Layer?
Facade patterns in a nutshell
Creating a service
Defining the User Service
Adding the CRUD methods
Adding the Gateway methods
Adding an abstract class
Defining the address service
onApplicationStart (revisited)
Summary
Index

Object-Oriented Programming in ColdFusion

Object-Oriented Programming in ColdFusion

Copyright © 2009 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: October 2010

Production Reference: 1081010

Published by Packt Publishing Ltd. 32 Lincoln Road Olton Birmingham, B27 6PA, UK.

ISBN 978-1-847196-32-3

www.packtpub.com

Cover Image by Filippo ( <[email protected]> )

Credits

Author

Matt Gifford

Reviewer

Raymond Camden

Acquisition Editor

David Barnes

Development Editor

Dhiraj Chandiramani

Rakesh Shejwal

Technical Editor

Arun Nadar

Copy Editor

Laxmi Subramanian

Indexer

Rekha Nair

Editorial Team Leader

Aditya Belpathak

Project Team Leader

Priya Mukherji

Project Coordinator

Leena Purkait

Proofreader

Lynda Sliwoski

Production Coordinator

Alwin Roy

Cover Work

Alwin Roy

Foreword

ColdFusion Components (or CFCs) were introduced in ColdFusion MX back in 2002, and since then they have become one of the most important and fundamental building blocks for ColdFusion developers. In fact, recent releases of ColdFusion have made CFC use mandatory, by introducing features that are only available through ColdFusion Components.

As you'd expect from ColdFusion, CFCs are easy to learn and even easier to use. But the beautiful simplicity of ColdFusion Components hides a powerful, sophisticated, and proven Java-based framework on which developers can build highly scalable and manageable applications. Like all ColdFusion features, CFCs can be as simple or as sophisticated as your application requires, and developers can start reaping their benefits easily and painlessly, adding functionality and complexity later as needed.

But this duel personality, highly accessible simplicity on the one hand and all that power on the other, has proven to be a bit of a double-edged sword. The same ease of use that makes ColdFusion so easy to learn and so productive, also makes it too easy to never fully explore and leverage all that ColdFusion has to offer.

This is why I am so glad to see Matt Gifford's hard work take the form of this book. Matt starts with the basics of ColdFusion Components, but then quickly delves into the subtleties and complexities of using them for object-oriented development, demonstrating both the how's and why's, as well as the tips and tricks needed to truly appreciate how ColdFusion Components can (and should) change the way you build your next ColdFusion application.

Matt, this book is long overdue, and your contribution to the ColdFusion community is greatly appreciated. Thanks!

Ben Forta

Director of Platform Evangelism

Adobe Systems

When you start using ColdFusion components, you know that you're on the right track; you can feel this change at some core, instinctual level as if you're about to embrace something that holds tremendous, yet untapped potential. Unfortunately, your instincts won't take you much further beyond this point. The cold reality is, Object-Oriented Programming (OOP), when used incorrectly, is a destructive force that can leave your code tightly coupled, brittle, and nearly impossible to maintain.

And yet, wave after wave of graduating computer scientists come to hail OOP as the only way to build robust and durable software. Now, this is not proof of a poor educational system; rather, it is a testament to the tried and true benefits of an object-oriented approach to software development. This commitment to OOP reinforces those instinctual feelings we experience as we type out the code "CFComponent"—we are on the right path to good development practice.

With great power comes great responsibility, and Object-Oriented Programming is a powerful tool. By reading this book and choosing to further your understanding of OOP, you are demonstrating great responsibility! Learning OOP the right way is the only responsible choice that you can make for yourself and for your clients.

Ben Nadel

Chief Software Engineer

Epicenter Consulting

To go Object-Oriented or to not go Object-Oriented (OO) is still the source of some of the most heated discussions in the ColdFusion world. The simple truth is that the rest of the programming world had this fight 10 years ago—and OO won. As a result of the wider industry's move towards OO, the ColdFusion community has also embraced this methodology; this has been done by adapting frameworks and patterns from other languages. The product teams at Adobe have adopted OO by introducing ColdFusion Components and Object Relational Mapping to the list of features within and available to ColdFusion.

Where does that leave the average ColdFusion developer, those people who don't have time to learn every new tag and function added to ColdFusion with each release? They're too busy working for a living, which makes finding the time and resources for ongoing professional development a real challenge.

Often it leaves these ColdFusion developers with no starting point, no easy onramp, to "get their OO on". This is a shame, and somewhat of an irony, as OO can be a highway to productivity. However, without a guide, exploring OO can be like travelling down a forested dirt road in the middle of the night. You can easily go off track.

That's why I was thrilled to hear that Matt Gifford had agreed to write the book you have in your hands. Matt is one of those hard to find technical minds that can communicate as well as he codes. I can think of no one better to help you navigate the sometimes tough, but always rewarding road that is Object-Oriented programming.

Terry Ryan

ColdFusion Evangelist

Adobe Systems

About the Author

Matt Gifford like many developers began his career teaching himself the basics of software development. Starting with simple applications using BASIC Programming on his Sinclair ZX Spectrum, he moved to creating relational databases in VBScript and hand-coding HTML pages in text editors. From at-home 'hobby' programming, Matt moved into the world of professional development in 2000 before getting a role as a web developer with the UNEP, where he was trained in ColdFusion. Matt later moved to agency and contract roles in London, where he also picked up new languages including Adobe Flex and AIR.

Now as a Lead Developer with Fuzzy Orange Ltd, Matt continues to specialize in ColdFusion, Flex, and AIR development. He presents regularly at national and international conferences and online meetings, and has written tutorials and articles for online resources and leading UK industry magazines.

As an Adobe Community Professional for ColdFusion, Matt is a keen proponent for community resources and sharing knowledge. He regularly writes and releases open source ColdFusion applications and code samples, which he shares through his blog, www.mattgifford.co.uk, as well as supporting the community online in forums and social media.

Acknowledgement

No publication or piece of work is ever the product of one individual, and these are just some of the people I need to thank.

Thank you to Douglas Paterson, Leena Purkait, and the Packt Publishing team who have helped guide me through all the challenges of writing my first book.

I would like to thank Ray Camden and Ben Nadel for technically reviewing this publication in various states and for providing suggestions and ideas from day one of this project.

Massive thanks goes out to John Whish, who shared his time so that we could discuss paradigms, patterns, and the intricacies of using cars as code examples.

Of course, thank you to the ColdFusion product team and to Adobe, for continuing to improve an already amazing product, and to the entire ColdFusion community, which justly deserves the reputation as being a supportive and committed group of professionals.

Finally, thank you to my amazing wife Cate who has supported me throughout this process, with patience, advice, and encouragement.

About the Reviewer

Raymond Camden is a software consultant focusing on ColdFusion and RIA development. A long time ColdFusion user, Raymond has worked on numerous ColdFusion books including the ColdFusion Web Application Construction Kit and has contributed to the Fusion Authority Quarterly Update and the ColdFusion Developers Journal. He also presents at conferences and contributes to online webzines. He founded many community websites including CFLib.org, ColdFusionPortal.org, and ColdFusionCookbook.org and is the author of open source applications, including the popular BlogCFC (www.blogcfc.com) blogging application. Raymond can be reached at his blog (www.coldfusionjedi.com) or through e-mail at <[email protected]>. He is the happily married proud father of three kids and is somewhat of a Star Wars nut.

Preface

The principles and fundamental elements of Object-Oriented Programming (OOP) are not new to the development world, although for some, there is a hesitancy to engage with OOP as it can be perceived as a confusing or unnecessary method of development.

As you read Object-Oriented Programming in ColdFusion, you will be guided through the core structure of ColdFusion Components, the foundation of OOP in CFML-based applications, and an introduction to some common design patterns and principles used in object-oriented development.

This book deals with the basic fundamental practices of OOP, including object creation and reuse, Bean objects, service layers, Data Access Objects, and simple design patterns. This is intended to help the reader gain a better understanding of OOP using examples that can be altered and applied into any application.

Object-Oriented Programming in ColdFusion aims to simplify the understanding of OOP, and dispense with unnecessary jargon and complex diagrams. By taking this more direct approach, this book aims to assist the reader in understanding the principles of OOP, how to implement them into their ColdFusion applications, and help the user extend their development skills in the process.

Using the practical examples within this easy-to-follow guide, you will learn how to structure your applications and code, and apply the fundamental basics of OOP to develop modular and reusable components that will scale easily with your application. This is ideal for any ColdFusion developer looking to break free from writing purely procedural code, and extend and advance their development practices.

Who this book is for

If you are a web developer wanting to implement object-oriented programming with ColdFusion, then this book is for you. If your goal is to get a good grounding in the basics of the object-oriented programming concepts, this book is perfect for you. No prior knowledge of object-oriented programming is expected, but basic knowledge of ColdFusion development skills is assumed.

What this book covers

Chapter 1, Introducing ColdFusion Components outlines the basic elements of ColdFusion Components. The reader is guided through the structure of a CFC, arguments, parameters, and encapsulating information.

Chapter 2, Effective Component Development highlights some important attributes and techniques to optimize your component's output. We also investigate introspecting a component as well as providing and reading metadata.

Chapter 3, Building Your First Bean begins the reader's journey into object-oriented development. This chapter focuses on a Bean object, understanding requirements and benefits for using one, and how to set and access properties within the Bean.

Chapter 4, Inheritance and Object-Oriented Concepts starts to explore the world of object-oriented programming in a little more detail. This chapter also introduces some key concepts such as polymorphism and composition.

Chapter 5, Data Access Objects looks at the use of Data Access Objects to access and obtain information from a data source. We'll also look at persisting objects in memory throughout your application.

Chapter 6, Gateways introduces an optional data access method for use in your object-oriented development, and also highlights some extra benefits of code separation to help enable easier code management within your applications.

Chapter 7, Creating a Service Layer introduces the use of facade objects to your application's underlying API / component structure. We also explore object inheritance and options to streamline the existing code within your framework.

What you need for this book

To get the most out of this publication, you will require version 8 or 9 of the ColdFusion server. You will also need a SQL database such as SQL server or MySQL to create a database to run the code examples.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to <[email protected]>, and mention the book title via the subject of your message.

If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or e-mail <[email protected]>.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Tip

Downloading the example code for this book

You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books maybe a mistake in the text or the code we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the errata submission form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.

Piracy

Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors, and our ability to bring you valuable content.

Questions

You can contact us at <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.

Chapter 1. Introducing ColdFusion Components

ColdFusion Components, commonly known as CFCs, were introduced in ColdFusion MX. In essence, they are simple templates written in existing CFML tags and CFScript. As such, they are not complex, confusing, or difficult to understand. If you can code CFML, you can create CFCs.

In this chapter, we will cover the following:

The basic structure of a ColdFusion componentThe component tags, functions, and methodsPassing parameters using the argument scope

For those with any experience with ColdFusion, components should be relatively commonplace. Object-Oriented Programming (OOP) relies heavily on the use of ColdFusion components, so before proceeding onto the ins and outs of OOP, let's re-familiarize ourselves with components within ColdFusion. This introduction will also serve as a reference when looking at subjects later in the book.

ColdFusion Components use the same ColdFusion Markup Language (CFML) as 'standard' ColdFusion pages. The core difference is the file extension—components must be saved with a .cfc file extension as opposed to the .cfm file extensions for template pages.

The basic structure of a ColdFusion Component is:

The component (the page within which you create the code to hold data or perform functions)The methods available to run within the CFC, also known as functions

In simple terms, CFCs themselves form a framework within ColdFusion, allowing you to write structured, clear, and organized code. They make application development easier to manage, control, and maintain.

Note

ColdFusion Components use the same CFML as 'standard' ColdFusion pages. The core difference is the file extension.

Why use CFCs?

It is not unusual for applications to grow and seem overly complex. Pages containing detailed information, such as business logic, data access and manipulation, data validation, and layout/presentation logic, can become untidy and hard to manage.

Creating and developing applications using CFCs enables you to separate the code logic from the design and presentation, and build an application based around, if not using, traditional Model View Controller (MVC) framework methodologies.

Utilizing CFCs and creating a clear structured format for your code will help reduce the complexity of logic within your pages and improve the application speed. Having a clearly structured, well organized code base will make it easier to develop as an individual and share resources within a team. This is the instant benefit of CFC development.

A well-written CFC will allow you to reuse your functions, or methods, across your entire application, helping to reduce the risk of code duplication. It will keep your component libraries and code base to a more easily manageable size, preventing it from becoming convoluted and difficult to follow.

ColdFusion components are an incredibly powerful and valuable means of creating efficient code. They allow you to:

Share properties and variables between other methods and functionsShare and interact with functions contained within other CFCsInherit the properties and methods of a base componentOverwrite methods and functions within other components

CFCs also give you the ability to clearly document and comment your code, letting you and other developers know what each function and property should do, what it should be expecting to receive to do the job and what output it will give you. ColdFusion components are able to read themselves and display this data to you, using a form of introspection, which we will cover in Chapter 2.