Welcome Guest, Not a member yet? Register   Sign In
  Active Record + Multiple Databases + Models
Posted by: El Forum - 03-26-2008, 10:59 AM - No Replies

[eluser]lookatthosemoose[/eluser]
Hiya everybody!

Question in regards to Active Record / Multiple Databases and their use in Models.


OK, so I've created 2 database connection groups in my DB config file.

Next, I (successfully) connect to the DBs in a controller like such:

Code:
function Login()
{
  parent::Controller();
  $MATRIX = $this->load->database('matrix',TRUE);
  $CAMPAIGN =  $this->load->database('campaign',TRUE);
}

Later in my controller, I want to invoke the function of a model (using active record) like such: EDIT - I'm aware the model isn't loaded in the code above, that's part of the question

Code:
function process(){
$code = $this->code->create();
}

"code" being the (active record) model where I want to run the query, like such:

Code:
class Code extends Model {


    function Code(){
        // Call the Model constructor
        parent::Model();
    }
    function create(){
        $query = $CAMPAIGN->get('codes',1);
    }
}

Initially, I was auto-loading my models in my autoload.php, which now I see I cannot do when using multiple DBs because (I think) I have to pass in the DB info when the model is loaded, either using this from what I found in the Docs:
Code:
$this->load->model('code', '', TRUE);   //autoload (I dont think this will work)

OR

Code:
$config['hostname'] = "localhost";
$config['username'] = "myusername";
$config['password'] = "mypassword";
$config['database'] = "mydatabase";
$config['dbdriver'] = "mysql";
$config['dbprefix'] = "";
$config['pconnect'] = FALSE;
$config['db_debug'] = TRUE;

$this->load->model('code', '', $config);

So 2 main questions:
1 - How would I access one of the DB connections from within my models.
2 - Without having to use the 2nd option above of passing in the DB config array?

I figure since it's already loaded as $CAMPAIGN and $MATRIX (above), I should be able to tell the model to use one of those. I hope this makes sense. Thanks!

--Eric--


  Want a little OO in your MVC?
Posted by: El Forum - 03-26-2008, 09:24 AM - Replies (5)

[eluser]bcdennis[/eluser]
After developing a little while in CI, I found myself wanting to develop a class hierarchy that violates the MVC architecture (as I understand it) implemented in CI. For instance, I have a calendaring type application going and I wanted a base class (called 'Schedulable') that I wanted all schedulable events to inherit from. But how do you do this as a CI model? Or a CI library? I know you could create a MY_Model that handles the basic scheduling routines for others to inherit from, but that didn't feel right to me. So what I did was as follows:

1.) Created a two new folders in the application folder; 'application/factories' and 'application/classes'.
2.) Created a new factory model who's responsibility is to instantiate object factories and assign any CI goodies needed to that factory. (such as $CI->db).
3.) Roll whatever classes I need into the 'application/classes' folder and create a matching factory in the 'application/factories' folder.

Snippet from 'models/factory_model.php'

Code:
class Factory_model extends model
{
    /**
     * Singleton for the Reservation Factory.
     *
     * @access    public
     * @param    none
     * @returns    object        The Reservation Factory object.
     */    
    public function reservation_factory()
    {
        if($this->reservation_factory == null)
        {
            require_once(APPPATH.'factories/reservation_factory'.EXT);
            $this->reservation_factory = new Reservation_factory();
            $this->reservation_factory->db =& $this->db;
        }

        return $this->reservation_factory;
    }
Snippet from 'factories/reservation_factory.php'
Code:
class Reservation_factory
{
    
     /**
     * Reservation Factory constructor.
     *  
     * @access    public
     * @param    none    
     * @return    none
     */        
    public function __construct()
     {
         require_once(APPPATH.'classes/base_class'.EXT);
         require_once(APPPATH.'classes/schedulable_class'.EXT);
         require_once(APPPATH.'classes/reservation_class'.EXT);
        log_message('debug', 'Reservation Factory Class Initialized');
     }

And then adding whatever factory methods I needed to the reservation_factory.

What I found is that this gives me another layer of abstraction with which to build my application. I can encapsulate logic specific to schedulable events in the schedulable class, while implementing a higher level of business logic in a calendar_model. So far, I'm getting smaller, more cohesive classes & models, which (to steal a phrase from Martin Fowler) just "smell's right".


Hope this helps anyone out there.


  Passing variables to custom validation callbacks
Posted by: El Forum - 03-26-2008, 08:40 AM - Replies (3)

[eluser]jamesf[/eluser]
Just a quick question, couldn't seem to find anything about it when I searched...

Is there a way of passing variables to your custom validation callbacks e.g.

Code:
$rules['username'] = "callback__valid_username($user_id)";

The project I'm working on allows 'admins' to create and edit 'users', when adding a new user I've created a function that will check the database for a duplicate username and this is working ok.

The problem comes when I'm editing a 'user', I need to do a check on the username whilst knowing the id of the user in question.

Regards,

James


  SimpleXMLElement
Posted by: El Forum - 03-26-2008, 06:32 AM - Replies (3)

[eluser]a.somervell[/eluser]
'nother question for the group:

Code:
$url = "http://maps.google.com/maps/geo?output=xml&key=ABQIAAAAnbn99sEqA=".str_replace(" ","+", preg_replace("/[^a-zA-Z0-9 ]/", "", preg_replace('/\s\s+/'," ", $address)));

try {
  $kml = new SimpleXMLElement( file_get_contents($url, "r"));
} catch (Exception $e) {
  //Do something exceptional...
}

If $address is say... "143" then the google XML will come back with a ridiculously long number of addresses, not idea but thats fine, I just go "found more than one address, please be more specific" to the user.

Problem is all the Japanese, Czech and other weird characters that come through that makes SimpleXMLElement go:

Code:
SimpleXMLElement::__construct() [function.SimpleXMLElement---construct]: Entity: line 1: parser error : Input is not proper UTF-8, indicate encoding ! Bytes: 0xFD 0x3C 0x2F 0x41

I figure I have to run the response through some sort of character translation function between getting the contents and passing it to SimpleXMLElement... But I cant figure out what that should be...?


  How to buildt dinamicly a controller?
Posted by: El Forum - 03-26-2008, 06:28 AM - Replies (6)

[eluser]Peter74[/eluser]
Hi all, iam building a site where the customers can show them products, i whish to show a url like this www.thedomain/customersite1 to www.thedomain/customersiteN but not from code
(i hope a lot of customers suscriptions xD), i dont know if iam thinking the good way, maybe u can help with something to start.

Very txs in advance

-----
sry about my poor inglish


  [Solved] Where factorize HTML code ?
Posted by: El Forum - 03-26-2008, 06:23 AM - Replies (9)

[eluser]Kromack[/eluser]
Hello everyone,

I'm using CI to remake my own little "CMS", I coded it in a two layers way, just with a template engine, some files likes controllers and libraries that look like models.

I used to call a function in my controllers that produce a box in a string way :

Code:
//We make a long string with all the code HTML of boxes
$box = makeBox($title, $content);
$box .= makeBox($anotherTitle, $anotherContent);

//We inject this code
$template->parse('myBoxes', $box);

I'm a little confused because, with CI i think I should write directly all the HTML code of all my boxes in a view.

Ok, but I have 10 boxes on a same page, it make a big view file and duplicated code... Also, instead of call one function, I have to copy / paste an entire bloc of HTML (corresponding to the box).

So my question is :

How to simplify my boxes management ?

Using an custom helper ? I have tryed but, controllers have to work with HTML (not good for MVC xD...)

Giving data to the views in order to they call an helper (Hum many PHP in views... not good for MVC xD...)

I hope I am clear, thank you for your help Smile


  Create a folder using code igniter?
Posted by: El Forum - 03-26-2008, 05:32 AM - Replies (1)

[eluser]JasonS[/eluser]
I can create files. But how do I create folder?

I need to create the following.

/root/cities/cityname/
/root/cities/cityname/images/

I have had a look at the file helper class but cannot see how I can use it to create folder. Does codeigniter have a built in function for this?

How would I edit and delete there folders along with their content.


  ActiveRecord using model in another model
Posted by: El Forum - 03-26-2008, 04:49 AM - Replies (5)

[eluser]flokky[/eluser]
I'm trying to find out what is the best approach to load a model within a model. I've searched and found some threads, but it doesn't quite answer my particular problem.

This is my (simplified) database structure:

Table: newscontent
id, title, content, date, category_id

Table: newscategory
id, categoryname

newscontent:category_id refers to newscategory:id.

How can I fetch the categoryname using the category_id? Sure, I can write a getCategoryName with the supplied category_id, but when using activeRecords I don't know how I can access the category_id, since my model doesn't have any modifiers (like in Java)

Code:
class News extends Controller {

    function News(){
        parent::Controller();
        
        $this->load->model('newssource', 'newssource');
        $this->load->model('newscontent', 'newscontent');
        $this->load->model('newscategory', 'newscategory');
        $this->load->helper('date');
    }
    
    function index(){
                //How can I fetch the category using getNewsContent?
        $news = $this->newscontent->getNewsContent($fields=null, $limit=null, $where=null);
        $data['news'] = $news->result();
        
                //Fetches all categories
        $categories = $this->newscategory->getNewsCategories($fields=null, $limit=null, $where=null);
        $data['categories'] = $categories->result();
        

        
        $this->load->vars($data);
        $this->load->view($this->_container);
    }
}

The model newscontent looks like this:
Code:
class Newscontent extends Model {

    function Newscontent(){  
    parent::Model();
        $this->_prefix = $this->config->item('FAL_table_prefix');
        $this->_table=$this->_prefix.'newscontent';
    }

    function getCategoryName() {
    $CI =& get_instance();
    $CI->load->model('newscategory','newscategory');
        
    $cat = $CI->newscategory->getCategoryById($this->category_id);
    $cat2 = $cat->result();
    return $cat2;
    }
    
    function getNewsContent($fields=null, $limit=null, $where=null) {    
    ($fields != null) ? $this->db->select($fields) :'';
        
    ($where != null) ? $this->db->where($where) :'';
        
    ($limit != null ? $this->db->limit($limit['start'], $limit['end']) : '');

    return $this->db->get($this->_table);
    }
    
   ...
}


  a problem with get_where
Posted by: El Forum - 03-26-2008, 03:33 AM - Replies (5)

[eluser]edhrx[/eluser]
Hi
this code
$query = $this->db->get_where('mem_sys_views', array('mode' => $mode,
'action' => $action));

Gives me this
Error Number: 1054

Unknown column 'form_id' in 'where clause'

SELECT * FROM (`mem_sys_views`) WHERE `form_id` = 'bfcebbbd76ff508773d7a974e308bae5' AND `mode` = 'member' AND `action` = 'edit'
Note form_id is not in the 'where' array

I'm guessing (at the moment)it comes from a previous call to where() or get_where()
Do I somehow need to 'clear' the where clause before creating another

I'm on the latest version of CI

best wishe Ed


  Force www. included in URL
Posted by: El Forum - 03-26-2008, 03:20 AM - Replies (3)

[eluser]iive[/eluser]
Hi, I would like to make sure all request to my site is in www.mysite.com instead of mysite.com. I do not know how to configure my .htaccess file to do that.

I have googled it a bit and I got a solution for that.. but it doesn't work properly if I combined it with my current .htacess file which hide the index.php from the URL.


.htaccess that force www in the url

Code:
RewriteCond %{HTTP_HOST} !^www.mysite.com$
RewriteRule ^(.*)$ http://www.mysite.com/$1 [R=301]

.htaccess that hide index.php from url
Code:
<IfModule mod_rewrite.c>
Options +FollowSymLinks
Options -Indexes
DirectoryIndex index.php
RewriteEngine on
RewriteCond $1 !(.jpg|.gif|.png|.swf|.css|.js|.txt)$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
</IfModule>
Anyone can help? I am not very good in apache. Sorry.


Welcome, Guest
You have to register before you can post on our site.

Username
  

Password
  





Latest Threads
Codeigniter 4 Model set()...
by kenjis
14 minutes ago
CI Builder Question
by InsiteFX
3 hours ago
SecurityException Status ...
by kenjis
10 hours ago
E-mail and UTF-8, mb_, et...
by joho
Yesterday, 07:13 AM
Shield validation questio...
by Codinglander
Yesterday, 07:07 AM
CI4 support MariaDB?
by joho
Yesterday, 07:06 AM
Using phpCas in CI4 (Comp...
by Zeff
Yesterday, 04:55 AM
where clause with order_b...
by kenjis
Yesterday, 01:55 AM
Transient support for Set...
by kenjis
Yesterday, 01:52 AM
Sharing things between CI...
by joho
Yesterday, 01:39 AM

Forum Statistics
» Members: 82,308
» Latest member: danigoldmobiletire
» Forum threads: 77,479
» Forum posts: 375,527

Full Statistics

Search Forums

(Advanced Search)


Theme © iAndrew 2016 - Forum software by © MyBB