Jifty - an application framework


Jifty documentation Contained in the Jifty distribution.

Index


Code Index:

NAME

Top

Jifty - an application framework

SYNOPSIS

Top

 # Object containing lots of web related goodies...
 my $web      = Jifty->web;
 my $request  = Jifty->web->request;
 my $response = Jifty->web->response;
 my $link     = Jifty->web->link( label => _('W00t'), url => '/whatsit' );

 # Retrieve information from your application's etc/config.yml file.
 my $config   = Jifty->config;

 # Retrieve the Jifty::DBI handle
 my $handle   = Jifty->handle;

 # Load an application class, very handy in plugins
 my $class    = Jifty->app_class('Model', 'Foo');
 my $foo      = $class->new;
 $foo->create( frobnicate => 42 );

 # Configure information related to your application's actions
 my $api      = Jifty->api;

 # Make parts of your page "subscribe" to information in a fragment
 my $subs     = Jifty->subs;

 # Share information via IPC::PubSub in your application
 my $bus      = Jifty->bus;

 # Retrieve general information about Mason
 my $handler  = Jifty->handler;

DESCRIPTION

Top

Yet another web framework.

What's cool about Jifty? (Buzzwords)

DRY (Don't Repeat Yourself)

Jifty tries not to make you say things more than once.

Full-stack

Out of the proverbial box, Jifty comes with one way to do everything you should need to do: One database mapper, one templating system, one web services layer, one AJAX toolkit, one set of handlers for standalone or FastCGI servers. We work hard to make all the bits play well together, so you don't have to.

Continuations

With Jifty, it's easy to let the user go off and do something else, like fill out a wizard, look something up in the help system or go twiddle their preferences and come right back to where they were.

Form-based dispatch

This is one of the things that Jifty does that we've not seen anywhere else. Jifty owns your form rendering and processing. This means you never need to write form handling logic. All you say is "I want an input for this argument here" and Jifty takes care of the rest. (Even autocomplete and validation)

A Pony

Jifty is the only web application framework that comes with a pony.

Introduction

If this is your first time using Jifty, Jifty::Manual::Tutorial is probably a better place to start.

METHODS

Top

new PARAMHASH

This class method instantiates a new Jifty object. This object deals with configuration files, logging and database handles for the system. Before this method returns, it calls the application's start method (i.e. MyApp->start) to handle any application-specific startup.

Most of the time, the server will call this for you to set up your Jifty object. If you are writing command-line programs that want to use your libraries (as opposed to web services) you will need to call this yourself.

See Jifty::Config for details on how to configure your Jifty application.

Arguments

no_handle

If this is set to true, Jifty will not create a Jifty::Handle and connect to a database. Only use this if you're about to drop the database or do something extreme like that; most of Jifty expects the handle to exist. Defaults to false.

logger_component

The name that Jifty::Logger will log under. If you don't specify anything Jifty::Logger will log under the empty string. See Jifty::Logger for more information.

config

An accessor for the Jifty::Config object that stores the configuration for the Jifty application.

logger

An accessor for our Jifty::Logger object for the application.

You probably aren't interested in this. See log for information on how to make log messages.

handler

An accessor for our Jifty::Handler object.

This is another method that you usually don't want to mess with too much. Most of the interesting web bits are handled by web.

handle

An accessor for the Jifty::Handle object that stores the database handle for the application.

api

An accessor for the Jifty::API object that publishes and controls information about the application's Jifty::Actions.

app_class(@names)

Return Class in application space. For example app_class('Model', 'Foo') returns YourApp::Model::Foo.

By the time you get it back, the class will have already been required

Is you pass a hashref as the first argument, it will be treated as configuration parameters. The only existing parameter is require, which defaults to true.

web

An accessor for the Jifty::Web object that the web interface uses.

subs

An accessor for the Jifty::Subs object that the subscription uses.

bus

Returns an IPC::PubSub object for the current application.

plugins

Returns a list of Jifty::Plugin objects for this Jifty application.

find_plugin

Find plugins by name.

class_loader

An accessor for the Jifty::ClassLoader object that stores the loaded classes for the application.

setup_database_connection

Set up our database connection. Optionally takes a paramhash with a single argument. This method is automatically called by new.

no_handle

Defaults to false. If true, Jifty won't try to set up a database handle

pre_init

Defaults to false. If true, plugins are notified that this is a pre-init, any trigger registration in init() should not happen during this stage. Note that model mixins' register_triggers is unrelated to this.

If no_handle is set or our application's config file is missing a Database configuration section or has a SkipDatabase: 1 directive in its framework configuration, does nothing.

app_instance_id

Returns a globally unique id for this instance of this jifty application. This value is generated the first time it's accessed

background SUB

Forks a background process, and ensures that database connections and sockets are not shared with the parent process.

admin_mode

Returns true if the application is in admin mode. This should be used instead of Jifty->config->framework('AdminMode').

SEE ALSO

Top

http://jifty.org, Jifty::Manual::Tutorial, Jifty::Everything, Jifty::Config, Jifty::Handle, Jifty::Logger, Jifty::Handler, Jifty::Web, Jifty::API, Jifty::Subs, IPC::PubSub, Jifty::Plugin, Jifty::ClassLoader

AUTHORS

Top

Jesse Vincent, Alex Vandiver and David Glasser.

LICENSE

Top

Jifty is Copyright 2005-2010 Best Practical Solutions, LLC. Jifty is distributed under the same terms as Perl itself.


Jifty documentation Contained in the Jifty distribution.
use warnings;
use strict;

package Jifty;
use IPC::PubSub 0.22;
use Data::UUID;
use encoding 'utf8';
use Class::Trigger;

BEGIN {
    # Work around the fact that Time::Local caches TZ on first require
    local $ENV{'TZ'} = "GMT";
    require Time::Local;

    # Declare early to make sure Jifty::Record::schema_version works
    $Jifty::VERSION = '1.10518';
}


use base qw/Jifty::Object/;
use Jifty::Everything;

use vars qw/$HANDLE $CONFIG $LOGGER $HANDLER $API $CLASS_LOADER $PUB_SUB $WEB @PLUGINS/;

sub new {
    my $ignored_class = shift;

    # Setup the defaults
    my %args = (
        no_handle        => 0,
        pre_init         => 0,
        logger_component => undef,
        @_
    );

    # Add the application's library path
    push @INC, File::Spec->catdir(Jifty::Util->app_root, "lib");

    # Now that we've loaded the configuration, we can remove the temporary 
    # Jifty::DBI::Record baseclass for records and insert our "real" baseclass,
    # which is likely Record::Cachable or Record::Memcached
    @Jifty::Record::ISA = grep { $_ ne 'Jifty::DBI::Record' } @Jifty::Record::ISA;

    # Configure the base class used by Jifty models
    my $record_base_class = Jifty->config->framework('Database')->{'RecordBaseClass'};
    Jifty::Util->require( $record_base_class );
    push @Jifty::Record::ISA, $record_base_class unless $record_base_class eq 'Jifty::Record';

    # Configure the base class for Jifty::CAS
    @Jifty::CAS::ISA = grep { $_ ne 'Jifty::CAS::Store' } @Jifty::CAS::ISA;
    my $cas_base = Jifty->config->framework('CAS')->{'BaseClass'};
    Jifty::Util->require( $cas_base );
    push @Jifty::CAS::ISA, $cas_base unless $cas_base eq 'Jifty::CAS';

    # Logger turn on
    Jifty->logger( Jifty::Logger->new( $args{'logger_component'} ) );

    # Set up plugins
    my @plugins;
    my @plugins_to_load = @{Jifty->config->framework('Plugins')};
    my $app_plugin = Jifty->app_class('Plugin');
    # we are pushing prereq to plugin, hence the 3-part for.
    for (my $i = 0; my $plugin = $plugins_to_load[$i]; $i++) {
        my $is_prereq = delete $plugin->{_prereq};

        # Prepare to learn the plugin class name
        my ($plugin_name) = keys %{$plugin};
        my $class;

        # Is the plugin name a fully-qualified class name?
        if ($plugin_name =~ /^(?:Jifty::Plugin|$app_plugin)::/) {
            # app-specific plugins use fully qualified names, Jifty plugins may
            $class = $plugin_name; 
        }

        # otherwise, assume it's a short name, qualify it
        else {
            $class = "Jifty::Plugin::".$plugin_name;
        }

        # avoid duplicating prereq plugins. we can't do this in the loop below
        # because a plugin might prereq a plugin later in config.yml
        if ($is_prereq) {
            my $this_class = qr/^(?:Jifty::Plugin::|\Q$app_plugin\E)?\Q$plugin_name\E$/;

            next if grep { $_ =~ $this_class } @plugins_to_load;

            # already loaded plugin objects
            next if grep { ref($_) =~ $this_class } @plugins;
        }

        # Load the plugin options
        my %options = (%{ $plugin->{ $plugin_name } },
                        _pre_init => $args{'pre_init'} );

        # Load the plugin code
        Jifty::Util->require($class);
        Jifty::ClassLoader->new(base => $class)->require;

        # Initialize the plugin and mark the prerequisites for loading too
        my $plugin_obj = $class->new(%options);
        push @plugins, $plugin_obj;
        foreach my $name ($plugin_obj->prereq_plugins) {
            push @plugins_to_load, {$name => {}, _prereq => 1};
        }
    }

    # All plugins loaded, save them for later reference
    Jifty->plugins(@plugins);

    # Now that we have the config set up and loaded plugins,
    # load the localization files.
    Jifty::I18N->refresh();
    
    # Get a classloader set up
    my $class_loader = Jifty::ClassLoader->new(
        base => Jifty->app_class,
    );

    # Save the class loader for later reference
    Jifty->class_loader($class_loader);
    $class_loader->require;

    # Configure the request handler and action API handler
    Jifty->handler(Jifty::Handler->new()) unless Jifty->handler;
    Jifty->api(Jifty::API->new()) unless Jifty->api;

    # We can only require view classes once we have our models and actions set.
    $class_loader->require_views;

    # Let's get the database rocking and rolling
    Jifty->setup_database_connection(%args);

    # Call the application's start method to let it do anything
    # application specific for startup
    my $app = Jifty->app_class;
    
    # Run the App::start() method if it exists for app-specific initialization
    $app->start
        if not $args{no_handle} and $app->can('start');

    # For plugins that want all the above initialization, but want to run before
    # we begin serving requests
    Jifty->call_trigger('post_init');
}

# Explicitly destroy the classloader; if this happens during global
# destruction, there's a period of time where there's a bogus entry in
# @INC
END {
    Jifty->class_loader->DESTROY if Jifty->class_loader;
}

sub config {
    my $class = shift;
    $CONFIG = shift if (@_);
    $CONFIG ||= Jifty::Config->new();
    return $CONFIG;
}

sub logger {
    my $class = shift;
    $LOGGER = shift if (@_);
    return $LOGGER;
}

sub handler {
    my $class = shift;
    $HANDLER = shift if (@_);
    return $HANDLER;
}

sub handle {
    my $class = shift;
    $HANDLE = shift if (@_);
    return $HANDLE;
}

sub api {
    my $class = shift;
    $API = shift if (@_);
    return $API;
}

sub app_class {
    shift;
    my $args = (ref $_[0] ? shift : { require => 1 });
    my $val = join('::', Jifty->config->framework('ApplicationClass'), @_);
    Jifty::Util->try_to_require($val) if $args->{require};
    return $val;
}

sub web {
    return $Jifty::WEB ||= Jifty::Web->new();
}

sub subs {
    return Jifty::Subs->new;
}

sub bus {
    my $class = shift;
    my %args = ( connect => 1, @_ );
    if (not $PUB_SUB and $args{connect}) {
        my @args;

        my $backend = Jifty->config->framework('PubSub')->{'Backend'};
        if ( $backend eq 'Memcached' ) {
            require IO::Socket::INET;

            # If there's a running memcached on the default port. this should become configurable
            if ( IO::Socket::INET->new('127.0.0.1:11211') ) {
                @args = ( Jifty->app_instance_id );
            } else {
                $backend = 'JiftyDBI';
            }
        } 
        
        if ($backend eq 'JiftyDBI' and Jifty->handle ) {
                @args    = (
                    db_config    => Jifty->handle->{db_config},
                    table_prefix => '_jifty_pubsub_',
                );
            }
        $PUB_SUB = IPC::PubSub->new( $backend => @args );

    }
    return $PUB_SUB;
}

sub plugins {
    my $class = shift;
    @PLUGINS = @_ if @_;
    return @PLUGINS;
}

sub find_plugin {
    my $self = shift;
    my $name = shift;

    my @plugins = grep { $_->isa($name) } Jifty->plugins;
    return wantarray ? @plugins : $plugins[0];
}

sub class_loader {
    my $class = shift;
    $CLASS_LOADER = shift if (@_);
    return $CLASS_LOADER;
}

sub setup_database_connection {
    my $self = shift;
    my %args = (no_handle  => 0,
                check_opts => {},
                @_);

    # Don't setup the database connection if we're told not to
    unless ( $args{'no_handle'}
        or Jifty->config->framework('SkipDatabase')
        or not Jifty->config->framework('Database') )
    {

        # Load the application's database handle and connect
        my $handle_class = Jifty->app_class("Handle");
        Jifty::Util->require( $handle_class );
        Jifty->handle( $handle_class->new );
        Jifty->handle->connect();

        # Clean out any stale Cache::Memcached connections
        $Jifty::DBI::Record::Memcached::MEMCACHED->disconnect_all
            if $Jifty::DBI::Record::Memcached::MEMCACHED;

        # Make sure the app version matches the database version
        Jifty->handle->check_schema_version(%{$args{'check_opts'}})
            unless $args{'no_version_check'};
    }
}


sub app_instance_id {
    my $self = shift;
    my $app_instance_id = Jifty::Model::Metadata->load("application_instance_uuid");
    unless ($app_instance_id) {
        require Data::UUID;
        $app_instance_id = Data::UUID->new->create_str();
        Jifty::Model::Metadata->store(application_instance_uuid => $app_instance_id );
    }
    return $app_instance_id;
}

sub background {
    my $class = shift;
    my $sub = shift;
    if (my $pid = fork) {
        return $pid;
    } else {
        close STDOUT;
        close STDIN;
        # XXX: make $Jifty::SERVER close client sockets if exists
        Jifty->handle->dbh->{InactiveDestroy} = 1;
        Jifty->setup_database_connection();
        $sub->();
        exit;
    }
}

sub admin_mode {
    return Jifty->config->framework('AdminMode')
        || Jifty->config->framework('SetupMode');
}

1;