Search Results

Search found 1591 results on 64 pages for 'oop criticism'.

Page 13/64 | < Previous Page | 9 10 11 12 13 14 15 16 17 18 19 20  | Next Page >

  • PDO using singleton stored as class properity

    - by Misiur
    Hi again. OOP drives me crazy. I can't move PDO to work. Here's my DB class: class DB extends PDO { public function &instance($dsn, $username = null, $password = null, $driver_options = array()) { static $instance = null; if($instance === null) { try { $instance = new self($dsn, $username, $password, $driver_options); } catch(PDOException $e) { throw new DBException($e->getMessage()); } } return $instance; } } It's okay when i do something like this: try { $db = new DB(DB_TYPE.':host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS); } catch(DBException $e) { echo $e->getMessage(); } But this: try { $db = DB::instance(DB_TYPE.':host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS); } catch(DBException $e) { echo $e->getMessage(); } Does nothing. I mean, even when I use wrong password/username, I don't get any exception. Second thing - I have class which is "heart" of my site: class Core { static private $instance; public $db; public function __construct() { if(!self::$instance) { $this->db = DB::instance(DB_TYPE.':hpost='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS); } return self::$instance; } private function __clone() { } } I've tried to use "new DB" inside class, but this: $r = $core->db->query("SELECT * FROM me_config"); print_r($r->fetch()); Return nothing. $sql = "SELECT * FROM me_config"; print_r($core->db->query($sql)); I get: PDOStatement Object ( [queryString] => SELECT * FROM me_config ) I'm really confused, what am I doing wrong?

    Read the article

  • iPhone Apps, Objective C, a Graph, and Functions vs. Objects (or something like that)

    - by BillEccles
    Gentleones, I've got a UIImageView that I have in a UIView. This particular UIImageView displays a PNG of a graph. It's important for this particular view controller and another view controller to know what the graph "looks like," i.e., the function described by the PNG graph. These other view controllers need to be able to call a "function" of some sort with the X value returning the Y value. Please ignore the fact (from an outsider's perspective) that I could probably generate the graph programmatically. So my questions are: 1 - Where should I put this function? Should it go in one view controller or the other, or should it go in its own class or main or...? 2 - Should it be an object in some way? Or should it be a straight function? (In either case, where's it belong?) Pardon the apparent n00b-iness of the question. It's 'cause I'm honestly a n00b! This OOP stuff is giving my head a spin having been a procedural programmer for 30 years. (And I choose to learn it by jumping into an iPhone app. Talk about baptism by fire!) Thanks in advance,Bill

    Read the article

  • Object Oriented Programming Problem

    - by Danny Love
    I'm designing a little CMS using PHP whilst putting OOP into practice. I've hit a problem though. I have a page class, whos constructor accepts a UID and a slug. This is then used to set the properties (unless the page don't exist in which case it would fail). Anyway, I wanted to implement a function to create a page, and I thought ... what's the best way to do this without overloading the constructor. What would the correct way, or more conventional method, of doing this be? My code is below: <?php class Page { private $dbc; private $title; private $description; private $image; private $tags; private $owner; private $timestamp; private $views; public function __construct($uid, $slug) { } public function getTitle() { return $this->title; } public function getDescription() { if($this->description != NULL) { return $this->description; } else { return false; } } public function getImage() { if($this->image != NULL) { return $this->image; } else { return false; } } public function getTags() { if($this->tags != NULL) { return $this->tags; } else { return false; } } public function getOwner() { return $this->owner; } public function getTimestamp() { return $this->timestamp; } public function getViews() { return $this->views; } public function createPage() { // Stuck? } }

    Read the article

  • Python calling class methods with the wrong number of parameters

    - by Hussain
    I'm just beginning to learn python. I wrote an example script to test OOP in python, but something very odd has happened. When I call a class method, Python is calling the function with one more parameter than given. Here is the code: 1. class Bar: 2. num1,num2 = 0,0 3. def __init__(num1,num2): 4. num1,num2 = num1,num2 5. def foo(): 6. if num1 num2: 7. print num1,'is greater than ',num2,'!' 8. elif num1 is num2: 9. print num1,' is equal to ',num2,'!' 10. else: 11. print num1,' is less than ',num2,'!' 12. a,b,t = 42,84,bar(a,b) 13. t.foo 14. 15. t.num1 = t.num1^t.num2 16. t.num2 = t.num2^t.num1 17. t.num1 = t.num1^t.num2 18. 19. t.foo 20. And the error message I get: python test.py Traceback (most recent call last): File "test.py", line 12, in a,b,t = 42,84,bar(a,b) NameError: name 'bar' is not defined Can anyone help? Thanks in advance

    Read the article

  • How to create a platform ontop of CSLA? <-- if in case it make sense

    - by Peejay
    Hi all! here is the senario, i'm developing an application using csla 3.8 / c#.net, the application will have different modules. its like an ERP, it will have accounting, daily time record, recruitment etc as modules. Now the requirement is to check for common entities per module and build a "platform" (<- the boss calls it that way) from it. for example, DTR will have an entity "employee", Recruitment will have "Applicant" so one common entity that you can derive from both that can be put in the platform is "Person". "Person" will contain typical info like name, address, contact info etc. I know it sounds like OOP 101. the thing is, i dont know how i am to go about it. how i wish it was just a simple inheritance but the requirement is like to create an API of some sort to be used by the modules using CSLA. in csla you create smart objects right, inheriting from the base classes of csla like businessListbase, readonlylistbase etc. right? what if for example i created a businessbase Applicant class, it will have properties like salary demand, availability date etc. now for the personal info i will need the "Person" from the "platform" and implement it to the applicant class. so in summary i have several questions: how to create such platform? if such platform is possible, how will it be implemented on each module's entities? (im already inheriting from base clases of csla) if incase 1 and 2 are possible, does it have advantages on development and maintenace of the app? the reason why i'm asking #3 is because the way i see it, even if i am able to create a platform for that, i will be needing to define properties of the platform entity on my module entities so to have validation and all. im sorry if i'm typing nonesense i'm really confused. hope someone could enlighten me. thank you all!

    Read the article

  • Imlpementations of an Interface with Different Types?

    - by b3njamin
    Searched as best I could but unfortunately I've learned nothing relevant; basically I'm trying to work around the following problem in C#... For example, I have three possible references (refA, refB, refC) and I need to load the correct one depending on a configuration option. So far however I can't see a way of doing it that doesn't require me to use the name of said referenced object all through the code (the referenced objects are provided, I can't change them). Hope the following code makes more sense: public ??? LoadedClass; public Init() { /* load the object, according to which version we need... */ if (Config.Version == "refA") { Namespace.refA LoadedClass = new refA(); } else if (Config.Version == "refB") { Namespace.refB LoadedClass = new refB(); } else if (Config.Version == "refC") { Namespace.refC LoadedClass = new refC(); } Run(); } private void Run(){ { LoadedClass.SomeProperty... LoadedClass.SomeMethod(){ etc... } } As you can see, I need the Loaded class to be public, so in my limited way I'm trying to change the type 'dynamically' as I load in which real class I want. Each of refA, refB and refC will implement the same properties and methods but with different names. Again, this is what I'm working with, not by my design. All that said, I tried to get my head around Interfaces (which sound like they're what I'm after) but I'm looking at them and seeing strict types - which makes sense to me, even if it's not useful to me. Any and all ideas and opinions are welcome and I'll clarify anything if necessary. Excuse any silly mistakes I've made in the terminology, I'm learning all this for the first time. I'm really enjoying working with an OOP language so far though - coming from PHP this stuff is blowing my mind :-)

    Read the article

  • Where to place interactive objects in JavaScript?

    - by Chris
    I'm creating a web based application (i.e. JavaScript with jQuery and lots of SVG) where the user interacts with "objects" on the screen (think of DIVs that can be draged around, resized and connected by arraows - like a vector drawing programm or a graphical programming language). As each "object" contains individual information but is allways belonging to a "class" of elements it's obvious that this application should be programmed by using an OOP approach. But where do I store the "objects" best? Should I create a global structure ("registry") with all (JS native) objects and tell them "draw yourself on the DOM"? Or should I avoid such a structure and think of the (relevant) DOM nodes as my objects and attach the relevant data as .data() to them? The first approach is very MVC - but I guess the attachment of all the event handlers will be non trivial. The second approach will handle the events in a trivial way and it doesn't create a duplicate structure, but I guess the usual OO stuff (like methods) will be more complex. What do you recomend? I think the answer will be JavaScript and SVG specific as "usual" programming languages don't have such a highly organized output "canvas".

    Read the article

  • C++ class derivation and superconstructor confusion

    - by LukeN
    Hey, in a tutorial C++ code, I found this particular piece of confusion: PlasmaTutorial1::PlasmaTutorial1(QObject *parent, const QVariantList &args) : Plasma::Applet(parent, args), // <- Okay, Plasma = namespace, Applet = class m_svg(this), // <- A member function of class "Applet"? m_icon("document") // <- ditto? { m_svg.setImagePath("widgets/background"); // this will get us the standard applet background, for free! setBackgroundHints(DefaultBackground); resize(200, 200); } I'm not new to object oriented programming, so class derivation and super-classes are nothing complicated, but this syntax here got me confused. The header file defines the class like this: class PlasmaTutorial1 : public Plasma::Applet { Similar to above, namespace Plasma and class Applet. But what's the public doing there? I fear that I already know the concept but don't grasp the C++ syntax/way of doing it. In this question I picked up that these are called "superconstructors", at least that's what stuck in my memory, but I don't get this to the full extend. If we glance back at the first snippet, we see Constructor::Class(...) : NS::SuperClass(...), all fine 'till here. But what are m_svg(this), m_icon("document") doing there? Is this some kind of method to make these particular functions known to the derivated class? Is this part of C++ basics or more immediate? While I'm not completly lost in C++, I feel much more at home in C :) Most of the OOP I have done so far was done in D, Ruby or Python. For example in D I would just define class MyClass : MySuperClass, override what I needed to and call the super class' constructor if I'd need to.

    Read the article

  • Why should I abstract my data layer?

    - by Gazillion
    OOP principles were difficult for me to grasp because for some reason I could never apply them to web development. As I developed more and more projects I started understanding how some parts of my code could use certain design patterns to make them easier to read, reuse, and maintain so I started to use it more and more. The one thing I still can't quite comprehend is why I should abstract my data layer. Basically if I need to print a list of items stored in my DB to the browser I do something along the lines of: $sql = 'SELECT * FROM table WHERE type = "type1"';' $result = mysql_query($sql); while($row = mysql_fetch_assoc($result)) { echo '<li>'.$row['name'].'</li>'; } I'm reading all these How-Tos or articles preaching about the greatness of PDO but I don't understand why. I don't seem to be saving any LoCs and I don't see how it would be more reusable because all the functions that I call above just seem to be encapsulated in a class but do the exact same thing. The only advantage I'm seeing to PDO are prepared statements. I'm not saying data abstraction is a bad thing, I'm asking these questions because I'm trying to design my current classes correctly and they need to connect to a DB so I figured I'd do this the right way. Maybe I'm just reading bad articles on the subject :) I would really appreciate any advice, links, or concrete real-life examples on the subject!

    Read the article

  • Codeigniter Inputting session data from model for a simple authentication system

    - by user1616244
    Trying to put together a simple login authentication. Been at this for quite sometime, and I can't find where I'm going wrong. Pretty new to Codeigniter and OOP PHP. I know there are authentication libraries out there, but I'm not interested in using those. Model: function login($username, $password){ if ($this->db->table_exists($username)){ $this->db->where('username', $username); $this->db->where('password', $password); $query = $this->db->get($username); if($query->num_rows >= 1) { return true; $data = array( 'username' => $this->input->post('username'), 'login' => true ); $this->session->set_userdata($data); } } } Controller function __construct(){ parent::__construct(); $this->logincheck(); } public function logincheck(){ if ($this->session->userdata('login')){ redirect('/members'); } } If I just echo from the controller: $this-session-all_userdata(); I get an empty array. So the problem seems to be that the $data array in the model isn't being stored in the session.

    Read the article

  • PHP OO vs Procedure with AJAX

    - by vener
    I currently have a AJAX heavy(almost everything) intranet webapp for a business. It is highly modularized(components and modules ala Joomla), with plenty of folders and files. ~ 80-100 different viewing pages (each very unique in it's own sense) on last count and will likely to increase in the near future. I based around the design around commands and screens, the client request a command and sends the required data and receives the data that is displayed via javascript on the screen. That said, there are generally two types of files, a display files with html, javascript, and a little php for templating. And also a php backend file with a single switch statement with actions such as, save, update and delete and maybe other function. There is very little code reuse. Recently, I have been adding an server sided undo function that requires me to reuse some code. So, I took the chance to try out OOP but I notice that some functions are so simple, that creating a class, retrieving all the data then update all the related rows on the database seems like overkill for a simple action as speed is quite critical. Also I noticed there is only one class in an entire file. So, what if the entire php is a class. So, between creating a class and methods, and using global variables and functions. Which is faster?

    Read the article

  • How can I get my business objects layer to use the management layer in their methods?

    - by Tom Pickles
    I have a solution in VS2010 with several projects, each making up a layer within my application. I have business entities which are currently objects with no methods, and I have a management layer which references the business entities layer in it's project. I now think I have designed my application poorly and would like to move methods from helper classes (which are in another layer) into methods I'll create within the business entities themselves. For example I have a VirtualMachine object, which uses a helper class to call a Reboot() method on it which passes the request to the management layer. The static manager class talks to an API that reboots the VM. I want to move the Reboot() method into the VirtualMachine object, but I will need to reference the management layer: public void Reboot() { VMManager.Reboot(this.Name); } So if I add a reference to my management project in my entities project, I get the circular dependency error, which is how it should be. How can I sort this situation out? Do I need to an yet another layer between the entity layer and the management layer? Or, should I just forget it and leave it as it is. The application works ok now, but I am concerned my design isn't particularly OOP centric and I would like to correct this.

    Read the article

  • Python: Calling method A from class A within class B?

    - by Tommo
    There are a number of questions that are similar to this, but none of the answers hits the spot - so please bear with me. I am trying my hardest to learn OOP using Python, but i keep running into errors (like this one) which just make me think this is all pointless and it would be easier to just use methods. Here is my code: class TheGUI(wx.Frame): def __init__(self, title, size): wx.Frame.__init__(self, None, 1, title, size=size) # The GUI is made ... textbox.TextCtrl(panel1, 1, pos=(67,7), size=(150, 20)) button1.Bind(wx.EVT_BUTTON, self.button1Click) self.Show(True) def button1Click(self, event): #It needs to do the LoadThread function! class WebParser: def LoadThread(self, thread_id): #It needs to get the contents of textbox! TheGUI = TheGUI("Text RPG", (500,500)) TheParser = WebParser TheApp.MainLoop() So the problem i am having is that the GUI class needs to use a function that is in the WebParser class, and the WebParser class needs to get text from a textbox that exists in the GUI class. I know i could do this by passing the objects around as parameters, but that seems utterly pointless, there must be a more logical way to do this that doesn't using classes seem so pointless? Thanks in advance!

    Read the article

  • Calling function and running it

    - by devs
    I am quite new to objects and OOP. I really don't know how to explain it well but I'll try. So I am trying to read though JSON with JS, the JSON is passed from PHP. This would be easy if all of the information was on the same html page, but I' am trying something that I am new too. So let me show my code... First is the JS which is in app.js var Donors = function(){ var api = this.list; $(document).ready(function(){ $.getJSON(api, function(){ var donorObj = api.payload; $.each(donorObj, function(i, donor){ //console.log(donor.ign); }); }); }); } What I want this part to do is read from the JSON I'm giving it and console.log each name (or donor.ign) when the document is ready. On the html page, or header.php <script> $(function(){ var list = <?php cbProxy(); ?>; var Dons = new Donors(); Dons.list = list; }); </script> the data that's in list is the below JSON. You already know what the rest does, it just passes the JSON to the Donors() function. JSON example: { "code": 0, "payload": [ { "time": 1349661897, "packages": [ "49381" ], "ign": "Notch", "price": "15.99", "currency": "USD" } I'm use to just making functions and calling it on the same page or file and this is my first doing this kind of function. How can I get the function to run with the data I sent it so it console.log() each name.

    Read the article

  • how to organize classes in ruby if they are literal subclasses

    - by RetroNoodle
    I know that title didn't make sense, Im sorry! Its hard to word what I am trying to ask. I had trouble googling it for the same reason. So this isn't even Ruby specific, but I am working in ruby and I am new to it, so bear with me. So you have a class that is a document. Inside each document, you have sentences, and each sentence has words. Words will have properties, like "noun" or a count of how many times they are used in the document, etc. I would like each of the elements, document, sentence, word be an object. Now, if you think literally - sentences are in documents, and words are in sentences. Should this be organized literally like this as well? Like inside the document class you will define and instantiate the sentence objects, and inside the sentence class you will define and instantiate the words? Or, should everything be separate and reference each other? Like the word class would sit outside the sentence class but the sentence class would be able to instantiate and work with words? This is a basic OOP question I guess, and I suppose you could argue to do it either way. What do you guys think? Each sentence in the document could be stored in a hash of sentence objects inside the document object, and each word in the sentence could be stored in a hash of word objects inside the sentence. I dont want to code myself into a corner here, thats why I am asking, plus I have wondered this before in other situations. Thank you!

    Read the article

  • Which open source PHP project has the 'perfect' OOP design I can learn from?

    - by aditya menon
    I am a newbie to OOP, and I learn best by example. You could say this question is similar to Which Scala open source projects should I study to learn best coding practices - but in PHP. I have heard-tell that Symfony has the best 'architecture' (I will not pretend I know what that exactly means), as well as Doctrine ORM. Is it worth it to spend many months reading the source code of these projects, trying to deduce the patterns used and learning new tricks? I have seen equal number of web pages dissing and liking Zend's codebase (will provide links if deemed necessary). Do you know of any other project that would make any veteran OOP developer shed tears of joy? Please let me add that practicality and scope of use is not a concern at all here - I just want to do: Pick a project that has a codebase deemed awesome by devs way better and greater than me. Write code that achieves what the project does. Compare results and try to learn what I don't know. Basically, an academic interest codebase. Any recommendations please?

    Read the article

  • OOP concept: is it possible to update the class of an instantiated object?

    - by Federico
    I am trying to write a simple program that should allow a user to save and display sets of heterogeneous, but somehow related data. For clarity sake, I will use a representative example of vehicles. The program flow is like this: The program creates a Garage object, which is basically a class that can contain a list of vehicles objects Then the users creates Vehicles objects, these Vehicles each have a property, lets say License Plate Nr. Once created, the Vehicle object get added to a list within the Garage object --Later on--, the user can specify that a given Vehicle object is in fact a Car object or a Truck object (thus giving access to some specific attributes such as Number of seats for the Car, or Cargo weight for the truck) At first sight, this might look like an OOP textbook question involving a base class and inheritance, but the problem is more subtle because at the object creation time (and until the user decides to give more info), the computer doesn't know the exact Vehicle type. Hence my question: how would you proceed to implement this program flow? Is OOP the way to go? Just to give an initial answer, here is what I've came up until now. There is only one Vehicle class and the various properties/values are handled by the main program (not the class) through a dictionary. However, I'm pretty sure that there must be a more elegant solution (I'm developing using VB.net): Public Class Garage Public GarageAdress As String Private _ListGarageVehicles As New List(Of Vehicles) Public Sub AddVehicle(Vehicle As Vehicles) _ListGarageVehicles.Add(Vehicle) End Sub End Class Public Class Vehicles Public LicensePlateNumber As String Public Enum VehicleTypes Generic = 0 Car = 1 Truck = 2 End Enum Public VehicleType As VehicleTypes Public DictVehicleProperties As New Dictionary(Of String, String) End Class NOTE that in the example above the public/private modifiers do not necessarily reflect the original code

    Read the article

  • Is this the correct approach to an OOP design structure in php?

    - by Silver89
    I'm converting a procedural based site to an OOP design to allow more easily manageable code in the future and so far have created the following structure: /classes /templates index.php With these classes: ConnectDB Games System User User -Moderator User -Administrator In the index.php file I have code that detects if any $_GET values are posted to determine on which page content to build (it's early so there's only one example and no default): function __autoload($className) { require "classes/".strtolower($className).".class.php"; } $db = new Connect; $db->connect(); $user = new User(); if(isset($_GET['gameId'])) { System::buildGame($gameId); } This then runs the BuildGame function in the system class which looks like the following and then uses gets in the Game Class to return values, such as $game->getTitle() in the template file template/play.php: function buildGame($gameId){ $game = new Game($gameId); $game->setRatio(900, 600); require 'templates/play.php'; } I also have .htaccess so that actual game page url works instead of passing the parameters to index.php Are there any major errors of how I'm setting this up or do I have the general idea of OOP correct?

    Read the article

  • Double Buffering for Game objects, what's a nice clean generic C++ way?

    - by Gary
    This is in C++. So, I'm starting from scratch writing a game engine for fun and learning from the ground up. One of the ideas I want to implement is to have game object state (a struct) be double-buffered. For instance, I can have subsystems updating the new game object data while a render thread is rendering from the old data by guaranteeing there is a consistent state stored within the game object (the data from last time). After rendering of old and updating of new is finished, I can swap buffers and do it again. Question is, what's a good forward-looking and generic OOP way to expose this to my classes while trying to hide implementation details as much as possible? Would like to know your thoughts and considerations. I was thinking operator overloading could be used, but how do I overload assign for a templated class's member within my buffer class? for instance, I think this is an example of what I want: doublebuffer<Vector3> data; data.x=5; //would write to the member x within the new buffer int a=data.x; //would read from the old buffer's x member data.x+=1; //I guess this shouldn't be allowed If this is possible, I could choose to enable or disable double-buffering structs without changing much code. This is what I was considering: template <class T> class doublebuffer{ T T1; T T2; T * current=T1; T * old=T2; public: doublebuffer(); ~doublebuffer(); void swap(); operator=()?... }; and a game object would be like this: struct MyObjectData{ int x; float afloat; } class MyObject: public Node { doublebuffer<MyObjectData> data; functions... } What I have right now is functions that return pointers to the old and new buffer, and I guess any classes that use them have to be aware of this. Is there a better way?

    Read the article

  • In a PHP project, how do you organize and access your helper objects?

    - by Pekka
    How do you organize and manage your helper objects like the database engine, user notification, error handling and so on in a PHP based, object oriented project? Say I have a large PHP CMS. The CMS is organized in various classes. A few examples: the database object user management an API to create/modify/delete items a messaging object to display messages to the end user a context handler that takes you to the right page a navigation bar class that shows buttons a logging object possibly, custom error handling etc. I am dealing with the eternal question, how to best make these objects accessible to each part of the system that needs it. my first apporach, many years ago was to have a $application global that contained initialized instances of these classes. global $application; $application->messageHandler->addMessage("Item successfully inserted"); I then changed over to the Singleton pattern and a factory function: $mh =&factory("messageHandler"); $mh->addMessage("Item successfully inserted"); but I'm not happy with that either. Unit tests and encapsulation become more and more important to me, and in my understanding the logic behind globals/singletons destroys the basic idea of OOP. Then there is of course the possibility of giving each object a number of pointers to the helper objects it needs, probably the very cleanest, resource-saving and testing-friendly way but I have doubts about the maintainability of this in the long run. Most PHP frameworks I have looked into use either the singleton pattern, or functions that access the initialized objects. Both fine approaches, but as I said I'm happy with neither. I would like to broaden my horizon on what is possible here and what others have done. I am looking for examples, additional ideas and pointers towards resources that discuss this from a long-term, real-world perspective. Also, I'm interested to hear about specialized, niche or plain weird approaches to the issue. Bounty I am following the popular vote in awarding the bounty, the answer which is probably also going to give me the most. Thank you for all your answers!

    Read the article

  • How do I call the methods in a model via controller? Zend Framework

    - by Joel
    Hi guys, I've been searching for tutorials to better understand this, but I'm having no luck. Please forgive the lengthy explination, but I want make sure I explain myself well. First, I'm quite new to the MVC structure, though I have been doing tutorials and learning as best I can. I have been moving over a live site into the Zend Framework model. So far, I have all the views within views/scripts/index/example.phtml. So therefore I'm using one IndexController and I have the code in each Action method for each page: IE public function exampleAction() Because I didn't know how to interact with a model, I put all the methods at the bottom of the controller (a fat controller). So basically, I had a working site by using a View and Controller and no model. ... Now I'm trying to learn how to incorporate the Model. So I created a View at: view/scripts/calendar/index.phtml I created a new Controller at: controller/CalendarControllers.php and a new model at: model/Calendar.php The problem is I think I'm not correctly communication with the model (I'm still new to OOP). Can you look over my controller and model and tell me if you see a problem. I'm needing to return an array from runCalendarScript(), but I'm not sure if I can return an array into the object like I'm trying to? I don't really understand how to "run" the runCalendarScript() from the controller? Thanks for any help! I'm stripping out most of the guts of the methods for the sake of brevity: controller: <?php class CalendarController extends Zend_Controller_Action { public function indexAction() { $finishedFeedArray = new Application_Model_Calendar(); $this->view->googleArray = $finishedFeedArray; } } model: <?php class Application_Model_Calendar { public function _runCalendarScript(){ $gcal = $this->_validateCalendarConnection(); $uncleanedFeedArray = $this->_getCalendarFeed($gcal); $finishedFeedArray = $this->_cleanFeed($uncleanedFeedArray); return $finishedFeedArray; } //Validate Google Calendar connection public function _validateCalendarConnection() { ... return $gcal; } //extracts googles calendar object into the $feed object public function _getCalendarFeed($gcal) { ... return $feed; } //cleans the feed to just text, etc protected function _cleanFeed($uncleanedFeedArray) { $contentText = $this->_cleanupText($event); $eventData = $this->_filterEventDetails($contentText); return $cleanedArray; } //Cleans up all formatting of text from Calendar feed public function _cleanupText($event) { ... return $contentText; } //filterEventDetails protected function _filterEventDetails($contentText) { ... return $data; } }

    Read the article

  • Refactoring Singleton Overuse

    - by drharris
    Today I had an epiphany, and it was that I was doing everything wrong. Some history: I inherited a C# application, which was really just a collection of static methods, a completely procedural mess of C# code. I refactored this the best I knew at the time, bringing in lots of post-college OOP knowledge. To make a long story short, many of the entities in code have turned out to be Singletons. Today I realized I needed 3 new classes, which would each follow the same Singleton pattern to match the rest of the software. If I keep tumbling down this slippery slope, eventually every class in my application will be Singleton, which will really be no logically different from the original group of static methods. I need help on rethinking this. I know about Dependency Injection, and that would generally be the strategy to use in breaking the Singleton curse. However, I have a few specific questions related to this refactoring, and all about best practices for doing so. How acceptable is the use of static variables to encapsulate configuration information? I have a brain block on using static, and I think it is due to an early OO class in college where the professor said static was bad. But, should I have to reconfigure the class every time I access it? When accessing hardware, is it ok to leave a static pointer to the addresses and variables needed, or should I continually perform Open() and Close() operations? Right now I have a single method acting as the controller. Specifically, I continually poll several external instruments (via hardware drivers) for data. Should this type of controller be the way to go, or should I spawn separate threads for each instrument at the program's startup? If the latter, how do I make this object oriented? Should I create classes called InstrumentAListener and InstrumentBListener? Or is there some standard way to approach this? Is there a better way to do global configuration? Right now I simply have Configuration.Instance.Foo sprinkled liberally throughout the code. Almost every class uses it, so perhaps keeping it as a Singleton makes sense. Any thoughts? A lot of my classes are things like SerialPortWriter or DataFileWriter, which must sit around waiting for this data to stream in. Since they are active the entire time, how should I arrange these in order to listen for the events generated when data comes in? Any other resources, books, or comments about how to get away from Singletons and other pattern overuse would be helpful.

    Read the article

  • Exceptions confusion

    - by Misiur
    Hi there. I'm trying to build site using OOP in PHP. Everyone is talking about Singleton, hermetization, MVC, and using exceptions. So I've tried to do it like this: Class building whole site: class Core { public $is_core; public $theme; private $db; public $language; private $info; static private $instance; public function __construct($lang = 'eng', $theme = 'default') { if(!self::$instance) { try { $this->db = new sdb(DB_TYPE.':host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS); } catch(PDOException $e) { throw new CoreException($e->getMessage()); } try { $this->language = new Language($lang); } catch(LangException $e) { throw new CoreException($e->getMessage()); } try { $this->theme = new Theme($theme); } catch(ThemeException $e) { throw new CoreException($e->getMessage()); } } return self::$instance; } public function getSite($what) { return $this->language->getLang(); } private function __clone() { } } Class managing themes class Theme { private $theme; public function __construct($name = 'default') { if(!is_dir("themes/$name")) { throw new ThemeException("Unable to load theme $name"); } else { $this->theme = $name; } } public function getTheme() { return $this->theme; } public function display($part) { if(!is_file("themes/$this->theme/$part.php")) { throw new ThemeException("Unable to load theme part: themes/$this->theme/$part.php"); } else { return 'So far so good'; } } } And usage: error_reporting(E_ALL); require_once('config.php'); require_once('functions.php'); try { $core = new Core(); } catch(CoreException $e) { echo 'Core Exception: '.$e->getMessage(); } echo $core->theme->getTheme(); echo "<br />"; echo $core->language->getLang(); try { $core->theme->display('footer'); } catch(ThemeException $e) { echo $e->getMessage(); } I don't like those exception handlers - i don't want to catch them like some pokemons... I want to use things simple: $core-theme-display('footer'); And if something is wrong, and debug mode is enabled, then aplication show error. What should i do?

    Read the article

  • What Programming Book would you NOT recommend to Developers?

    - by Ender
    Like a lot of people on Stack Overflow I love to read books about programming, almost as much as I love to read the lists that people add onto their websites, Blog's and this very website. However, for every gem there are a thousand turds, and to one developer a gem could just be a shiny turd to another. Whilst there are hundreds of book questions on this website asking users to recommend books that they have loved I have decided (after looking for a similar question and not finding it) to create a list of books that users have detested. After all, if we're going to fork out money for these books it'd be a good idea to get both positive and negative aspects out there. Please refer to a specific book, and with it add an image of either the latest version or the version you have read. Also, if you have the time please comment on the answers to provide your experiences with the books.

    Read the article

  • Exporting a non public Type through public API

    - by sachin
    I am trying to follow Trees tutorial at: http://cslibrary.stanford.edu/110/BinaryTrees.html Here is the code I have written so far: package trees.bst; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; /** * * @author sachin */ public class BinarySearchTree { Node root = null; class Node { Node left = null; Node right = null; int data = 0; public Node(int data) { this.left = null; this.right = null; this.data = data; } } public void insert(int data) { root = insert(data, root); } public boolean lookup(int data) { return lookup(data, root); } public void buildTree(int numNodes) { for (int i = 0; i < numNodes; i++) { int num = (int) (Math.random() * 10); System.out.println("Inserting number:" + num); insert(num); } } public int size() { return size(root); } public int maxDepth() { return maxDepth(root); } public int minValue() { return minValue(root); } public int maxValue() { return maxValue(root); } public void printTree() { //inorder traversal System.out.println("inorder traversal:"); printTree(root); System.out.println("\n--------------"); } public void printPostorder() { //inorder traversal System.out.println("printPostorder traversal:"); printPostorder(root); System.out.println("\n--------------"); } public int buildTreeFromOutputString(String op) { root = null; int i = 0; StringTokenizer st = new StringTokenizer(op); while (st.hasMoreTokens()) { String stNum = st.nextToken(); int num = Integer.parseInt(stNum); System.out.println("buildTreeFromOutputString: Inserting number:" + num); insert(num); i++; } return i; } public boolean hasPathSum(int pathsum) { return hasPathSum(pathsum, root); } public void mirror() { mirror(root); } public void doubleTree() { doubleTree(root); } public boolean sameTree(BinarySearchTree bst) { //is this tree same as another given tree? return sameTree(this.root, bst.getRoot()); } public void printPaths() { if (root == null) { System.out.println("print path sum: tree is empty"); } List pathSoFar = new ArrayList(); printPaths(root, pathSoFar); } ///-------------------------------------------Public helper functions public Node getRoot() { return root; } //Exporting a non public Type through public API ///-------------------------------------------Helper Functions private boolean isLeaf(Node node) { if (node == null) { return false; } if (node.left == null && node.right == null) { return true; } return false; } ///----------------------------------------------------------- private boolean sameTree(Node n1, Node n2) { if ((n1 == null && n2 == null)) { return true; } else { if ((n1 == null || n2 == null)) { return false; } else { if ((n1.data == n2.data)) { return (sameTree(n1.left, n2.left) && sameTree(n1.right, n2.right)); } } } return false; } private void doubleTree(Node node) { //create a copy //bypass the copy to continue looping if (node == null) { return; } Node copyNode = new Node(node.data); Node temp = node.left; node.left = copyNode; copyNode.left = temp; doubleTree(copyNode.left); doubleTree(node.right); } private void mirror(Node node) { if (node == null) { return; } Node temp = node.left; node.left = node.right; node.right = temp; mirror(node.left); mirror(node.right); } private void printPaths(Node node, List pathSoFar) { if (node == null) { return; } pathSoFar.add(node.data); if (isLeaf(node)) { System.out.println("path in tree:" + pathSoFar); pathSoFar.remove(pathSoFar.lastIndexOf(node.data)); //only the current node, a node.data may be duplicated return; } else { printPaths(node.left, pathSoFar); printPaths(node.right, pathSoFar); } } private boolean hasPathSum(int pathsum, Node node) { if (node == null) { return false; } int val = pathsum - node.data; boolean ret = false; if (val == 0 && isLeaf(node)) { ret = true; } else if (val == 0 && !isLeaf(node)) { ret = false; } else if (val != 0 && isLeaf(node)) { ret = false; } else if (val != 0 && !isLeaf(node)) { //recurse further ret = hasPathSum(val, node.left) || hasPathSum(val, node.right); } return ret; } private void printPostorder(Node node) { //inorder traversal if (node == null) { return; } printPostorder(node.left); printPostorder(node.right); System.out.print(" " + node.data); } private void printTree(Node node) { //inorder traversal if (node == null) { return; } printTree(node.left); System.out.print(" " + node.data); printTree(node.right); } private int minValue(Node node) { if (node == null) { //error case: this is not supported return -1; } if (node.left == null) { return node.data; } else { return minValue(node.left); } } private int maxValue(Node node) { if (node == null) { //error case: this is not supported return -1; } if (node.right == null) { return node.data; } else { return maxValue(node.right); } } private int maxDepth(Node node) { if (node == null || (node.left == null && node.right == null)) { return 0; } int ldepth = 1 + maxDepth(node.left); int rdepth = 1 + maxDepth(node.right); if (ldepth > rdepth) { return ldepth; } else { return rdepth; } } private int size(Node node) { if (node == null) { return 0; } return 1 + size(node.left) + size(node.right); } private Node insert(int data, Node node) { if (node == null) { node = new Node(data); } else if (data <= node.data) { node.left = insert(data, node.left); } else { node.right = insert(data, node.right); } //control should never reach here; return node; } private boolean lookup(int data, Node node) { if (node == null) { return false; } if (node.data == data) { return true; } if (data < node.data) { return lookup(data, node.left); } else { return lookup(data, node.right); } } public static void main(String[] args) { BinarySearchTree bst = new BinarySearchTree(); int treesize = 5; bst.buildTree(treesize); //treesize = bst.buildTreeFromOutputString("4 4 4 6 7"); treesize = bst.buildTreeFromOutputString("3 4 6 3 6"); //treesize = bst.buildTreeFromOutputString("10"); for (int i = 0; i < treesize; i++) { System.out.println("Searching:" + i + " found:" + bst.lookup(i)); } System.out.println("tree size:" + bst.size()); System.out.println("maxDepth :" + bst.maxDepth()); System.out.println("minvalue :" + bst.minValue()); System.out.println("maxvalue :" + bst.maxValue()); bst.printTree(); bst.printPostorder(); int pathSum = 10; System.out.println("hasPathSum " + pathSum + ":" + bst.hasPathSum(pathSum)); pathSum = 6; System.out.println("hasPathSum " + pathSum + ":" + bst.hasPathSum(pathSum)); pathSum = 19; System.out.println("hasPathSum " + pathSum + ":" + bst.hasPathSum(pathSum)); bst.printPaths(); bst.printTree(); //bst.mirror(); System.out.println("Tree after mirror function:"); bst.printTree(); //bst.doubleTree(); System.out.println("Tree after double function:"); bst.printTree(); System.out.println("tree size:" + bst.size()); System.out.println("Same tree:" + bst.sameTree(bst)); BinarySearchTree bst2 = new BinarySearchTree(); bst2.buildTree(treesize); treesize = bst2.buildTreeFromOutputString("3 4 6 3 6"); bst2.printTree(); System.out.println("Same tree:" + bst.sameTree(bst2)); System.out.println("---"); } } Now the problem is that netbeans shows Warning: Exporting a non public Type through public API for function getRoot(). I write this function to get root of tree to be used in sameTree() function, to help comparison of "this" with given tree. Perhaps this is a OOP design issue... How should I restructure the above code that I do not get this warning and what is the concept I am missing here?

    Read the article

< Previous Page | 9 10 11 12 13 14 15 16 17 18 19 20  | Next Page >